c++ - Why is the contents of the vector being printed wrong here? -


#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 output 1 2 3 4 received output shown below:

image

the push_back can change begin , end iterators if new item doesn't fit in vector-capacity (the internal size). in example push_back implies reallocation of internal buffer , begin , end iterators new values. problem in example end-iterator evaluated each step , gets new value begin iterator still keeping old(invalid) value , causes undefined behavior. following changes illustrate 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 can see, begin , end iterators changes completely

show result


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -