Push_back() in vector is behaving weird

92 Views Asked by At

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;
} 
1

There are 1 best solutions below

0
Chris On

Modifying v in the loop invalidates the iterator a you've created, leading to undefined behavior.

From the CPPReference page on the push_back function:

If after the operation the new size() is greater than old capacity() a reallocation takes place, in which case all iterators (including the end() iterator) and all references to the elements are invalidated. Otherwise only the end() iterator is invalidated.