C ++ class for arrays with arbitrary indices

Are there any classes (or classes) in any popular C ++ libraries that allow the developer to use arrays with arbitrary indices without sacrificing speed?

To give this question a more specific form, I would like to write code like the one below:

//An array with indices in [-5,6)
ArbitraryIndicesArray<int> a = ArbitraryIndicesArray<int>(-5,6);  
for(int index = -5;index < 6;++index)
{
    a[index] = index;
}
+3
source share
5 answers

Indeed, you should use an offset vector. Or even an array with an offset. Additional addition or subtraction will not make any difference to the speed of the program.

If you want something at the same speed as the default C array, you can apply the offset to the array pointer:

int* a = new int[10];
a = a + 5;
a[-1] = 1;

. , - , . C, .

, . reset . , , .

//resetting the array by adding the offset (of -5)
delete [] (a - 5);
+6

A std::vector<int> .
O (1).

, setset.

+4

STL:

std::map<int, int> a;
for( int index = -5; index < 6; ++index )
{ 
    a[index] = index; 
}

, .

+2

[ , ...]

Boost.MultiArray .

ObjexxFCL .

. OP 1D , std::vector .

+1

, .

std::vector operator[]:

template <class T>
class ArbVector
{
    private:
        int _offset;
        std::vector<T> container;
    public:
        ArbVector(int offset) : _offset(offset) {}
        T& operator[](int n) { return container[n + _offset] }
};

, , .

std::vector, . .

0
source

Source: https://habr.com/ru/post/1733917/


All Articles