Reputation: 914
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int test=0;
vector<int>v{1,2,3};
for(auto i=v.cbegin();i!=v.cend();++i)
{
++test;
if(test==2)
{
v.push_back(4);
}
cout<<*i<<endl;
}
return 0;
}
I expected the output to be only 1 2 3 4
but I received the output as shown below:
Upvotes: 1
Views: 74
Reputation: 1245
The push_back can change the begin and end iterators if the new item doesn't fit in the vector-capacity (the internal size). In your example the push_back implies a reallocation of the internal buffer and the begin and end iterators get new values. The problem in your example is the end-iterator will be evaluated for each step and it gets the new value but the begin Iterator is still keeping the old(invalid) value and that causes undefined behavior. Following changes will illustrate what happens:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
int test=0;
vector<int>v{1,2,3};
for(auto i=v.cbegin();i!=v.cend();++i)
{
++test;
if(test==2)
{
std::cout << &*v.cbegin()<<std::endl;
std::cout << &*v.cend()<<std::endl;
v.push_back(4);
std::cout << &*v.cbegin()<<std::endl;
std::cout << &*v.cend()<<std::endl;
}
cout<<*i<<endl;
}
return 0;
}
As you can see, the begin and end iterators changes completely
Upvotes: 3