constant elements vector

Dec 12, 2012 at 10:22pm
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
const int a = 3;
const int 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 <const int> vec;
//or this as well
const std::vector <int> vec;
Dec 12, 2012 at 10:47pm
a and b are constant, you can't change them.

vec isn't constant, you can change it and the values it holds.
Dec 12, 2012 at 10:50pm
how to make vec constant then??
Dec 12, 2012 at 10:56pm
With STL containers, the value type is required to be assignable. (not const)
 
vector<const int> 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.
}
Last edited on Dec 12, 2012 at 10:58pm
Topic archived. No new replies allowed.