0

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.

Wasim Thabraze
  • 780
  • 1
  • 12
  • 29

2 Answers2

3

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];
    }
};

Demo on ideone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Is this a bit of overkill? I like @CiaPan's answer, a lot simpler. – Thomas Matthews May 21 '14 at 17:58
  • 1
    @ThomasMatthews When you need an offset like 2, yes, it's an overkill. When you want an offset like 200000 or -5, it's not an overkill. – Sergey Kalinichenko May 21 '14 at 18:00
  • I would even say that an offset of "2" is dangerous and is not overkill to create a class to handle such "simple" cases. I have seen too many times when a programmer tries the simple approach and then wound up debugging off-by-1 errors somewhere down the road. – PaulMcKenzie May 21 '14 at 18:18
2

Just allocate the array two items longer than you need and ignore items at index 0 and 1.

CiaPan
  • 9,381
  • 2
  • 21
  • 35
  • The problem with this is not that it wouldn't work in the short run. The issue occurs (and I've seen it time and again) when a programmer tries to fake out non-zero based arrays in C++ using such simple means. Somewhere at sometime, the programmer gets "off-by-1" or worse errors. Better to create a class that can detect misuse than to simply allocate an array. – PaulMcKenzie May 21 '14 at 18:12