Expected output is : 1 2 3 4 and if we uncomment line mentioned which does the push back operation and run the code the expected output is still 1 2 3 4. But guess what its totally different. Run it and you will know. why does that happen?
#include <iostream>
#include<vector>
using namespace std;
int main()
{
int k=2;
vector<int> v;
vector<int> :: iterator itr;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
v.push_back(6);
v.push_back(7);
auto a=v.begin();
for(int i=0;i<4;i++){
cout<<*a<<" ";
//v.push_back(anynumber); ----------------------------------->This line
a++;
}
return 0;
}
Modifying
vin the loop invalidates the iteratorayou've created, leading to undefined behavior.From the CPPReference page on the
push_backfunction: