c++11 - Strange behaviour of for_each and push_back() -
i doing testing for_each , use of lambda functions , i'm stuck on (compiled g++ -std=c++11, gcc version 5.3.1)
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> vi = {1,1,1,1}; int end =0; cout << "vi contains: "; for_each(vi.begin(), vi.end(),[](int i){ cout << << " "; }); cout << endl; for_each(vi.begin(),vi.end(),[&](int i){ cout << "i="<<i<<" "; if(i==1){ vi.push_back(1); end++; } }); cout << endl; cout << "end=" << end << endl; cout << "now vi contains: "; for_each(vi.begin(), vi.end(),[](int i){ cout << << " "; }); cout << endl; return 0; }
and output of code
vi contains: 1 1 1 1 i=1 **i=0** i=1 i=1 end=3 vi contains: 1 1 1 1 1 1 1
why is, @ first iteration of loop, equal 0?
Comments
Post a Comment