c++ - why vector does not updates in loop? -
i want update vector 'v' can iterate count 0-100.
i know not allowed, if want only? there way?
int main() { // code goes here vector<int> v; v.push_back(1); int count = 0; for(int elem: v){ if(count<100) v.push_back(count); count++; } for(int elem: v) cout << elem << endl; homecoming 0; }
the output is:
1 0
as can see definition of range-based loop, end_expr not update between iterations. hence have 1 iteration. push_back
invalidates v.end()
(which end_expr described in linked page), have undefined behaviour.
the arguably simplest way fill vector 0..100 be:
vector<int> v(101); std::iota(v.begin(), v.end(), 0);
c++ c++11 vector
No comments:
Post a Comment