Reputation: 175
Please explain why the following code works as expected (the element is added at the 2nd position):
std::vector<int> v(5);
for(int i = 0; i < 5; i++)
v[i] = i;
std::vector<int>::iterator it = v.begin()+1;
it = v.insert(it, 33);
cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
//outs: 0 33 1 2 3
and the following doesn't (the element is added at first position):
std::vector<int> v;
v.reserve(5);
for(int i = 0; i < 5; i++)
v[i] = i;
std::vector<int>::iterator it = v.begin()+1;
it = v.insert(it, 33);
cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
//outs: 33 1 2 3 4
Upvotes: 0
Views: 128
Reputation: 2122
std::vector<int> v(5);
Creates a 5 element vector
std::vector<int> v;
v.reserve(5);
Creates an empty vector, but allocates room to push back 5 elements later
so trying to access v[i]
is undefined behaviour, since the vector doesn't actually contain any elements at this point.
Your second example could be changed to:
std::vector<int> v;
v.resize(5);
for(int i = 0; i < 5; i++)
v[i] = i;
This properly creates a 5 element vector (you could use this when you don't initially know the size at the time you allocate the vector)
or
std::vector<int> v;
v.reserve(5);
for(int i = 0; i < 5; i++)
v.push_back(i);
Which reserves space for 5 elements, which get inserted in order (this would be commonly used when you know beforehand how many elements you have, but each element doesn't need to know what index it is to be inserted at - each one just gets added to the end of the vector.
Note, in either case, you can still add additional items - the vector will just get resized. To keep your code optimal, the aim is to try and keep to a minimum the number of times your vector does get resized.
Upvotes: 2
Reputation: 227578
It is undefined behaviour. std::vector::reserve
does not resize the vector, so calling v[i]
is an out of bounds access.
You need to either call v.resize(5)
to expand the vector to hold 5 elements, or call v.push_back
inside the loop.
Upvotes: 6