std:vector<T> of arbitrary size and arbitrary starting point

Viewed 62

Say I want a std:vector<T>, and say I have 1000 elements of T. The index into T has an arbitrary starting point, say 15000 to 16000 (1000 elements).

Without allocating 16000 elements, how do I create the vector<T> so that 15000 is index, 1, 15001 is index 2, etc.

I know I can do this with a Hash, but my indices are naturally integers in the range of 15000 to 16000.

I can probably also inherit my own class from Vector and overload operator [], so that 15000 is converted into 1, etc, but I am just wondering if there is a commodity version of this out there.

1 Answers

AFAIK, std::vector's index is not variable, it always starts at 0. You could either manually substract 15000 from your index like so:

for(int i = 15000; i < 16000; i++) {
    std::cout < vector[i - 15000] << std::endl;
}

or create a class that does it for you:

#include <vector>
#include <iostream>

template<typename T>
class VectorWrap : public std::vector<T> {
  typedef std::vector<T> super;
  size_t index_base;
public:
  VectorWrap(size_t index) : index_base{index} {}

  typename super::reference at(size_t pos) {
    return super::at(pos - index_base);
  }
  typename super::reference operator[](size_t pos) {
    return super::operator[](pos - index_base);
  }
};

int main(int argc, char** argv) {
  VectorWrap<int> vw{15000};
  vw.push_back(5);
  vw.push_back(6);
  vw.push_back(7);

  std::cout << vw[15000] << std::endl;
  vw[15000] = 1;
  std::cout << vw[15000] << std::endl;
}
Related