How to implement an array in C++ so that the index of the first element is 2. In other words instead of index starting from '0', I want indexing from '2'. Is it possible?
Thanks in advance.
How to implement an array in C++ so that the index of the first element is 2. In other words instead of index starting from '0', I want indexing from '2'. Is it possible?
Thanks in advance.
 
    
    Although built-in arrays of C++ have their index starting at zero, you can build an array-like class with an index starting at any number, even a negative one.
The key to building a class like that is overriding the square brackets operator [] with an implementation translating the incoming index to the index of the actual array encapsulated within your implementation by subtracting the offset.
Here is a sketch of an implementation that uses vector<T> for the data:
class array_with_offset {
    int offset;
    vector<int> data;
public:
    array_with_offset(int N, int off)
    :   offset(off), data(N) {
    }
    int& operator[](int index) {
        return data[index-offset];
    }
};
 
    
    Just allocate the array two items longer than you need and ignore items at index 0 and 1.
