In C++ I wish to allocate a fixed-size (but size determined at runtime) std::vector then write to the elements in this vector. This is the code I am using:
int b = 30;
const std::vector<int> test(b);
int &a = test[3];
However, this gives me a compiler (MSVC 2010 Pro) error:
error C2440: 'initializing' : cannot convert from 'const int' to 'int &'. Conversion loses qualifiers.
My understanding of const is that it makes all of the member variables of a class constant. For example, the following works fine:
class myvec
{
public:
myvec(int num) : ptr_m(new int[num]) {};
~myvec() { delete ptr_m; }
void resize(int num) { delete ptr_m; ptr_m = new int[num]; }
int & operator[] (int i) const { return ptr_m[i]; }
int *ptr_m;
};
const myvec test(30);
int &a = test[3]; // This is fine, as desired
test.resize(10); // Error here, as expected
It would therefore seem that std::vector propagates the const-ness of the container to the elements of the vector, which seems odd because if I had wanted the elements to be const I would have used std::vector<const int>. This therefore strikes me as a shortcoming of std::vector.
In any case, how can I create a std::vector whose size cannot be changed after construction, but whose elements can be written to?