I'm experimenting with constants. I would like to append few elements in vector which will remain constant. For eg:
1 2 3 4 5 6 7 8
constint a = 3;
constint b = 5;
std::vector <int> vec;
vec.push_back(a);
vec.push_back(b);
vec[0] = 1000; //const int a is appended at index 0 but it can still be
//moddified ?
std::cout << vec[0] << "\n"; //1000 is returned what i want is an error
Does that mean that a copy is appended which is not constant? I've tried doing this too but without any success.
1 2 3
std::vector <constint> vec;
//or this as well
const std::vector <int> vec;
With STL containers, the value type is required to be assignable. (not const)
vector<constint> v; //will decay to vector<int>.
Having vectors full of const items isn't of much use, however.
One thing you can do is declare the entire container as const. This way, you will not be able to apply any changes to the container (including adding or removing items.)
This is useful if you're passing a vector to another function, and don't want it to modify the vector. So you can explicitly tell the function not to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
vector<int> v;
v.push_back(10);
v.push_back(50);
v.push_back(8);
someFunction(v);
}
void someFunction(const &vector<int> vec) //function is unable to modify vec
{
vec[0] = 5; //will not compile, cannot change any values of a const vector.
}