C++: push_back in std::vector while iterating it
问题 Following code snippet provides a very weird output. I was expecting an overflow( Python gives a MemoryError) #include <iostream> #include <vector> int main() { std::vector<int> a{1,2,3}; for( auto const & item : a) a.push_back(item); for( auto const & item : a) std::cout<<item<<','; return 0; } Output: 1,2,3,1,0,3, How do I interpret this result? If you do a similar thing in Python, it gives a memory error. >>> a = range(0,20) >>> for i in a: a.append(i) Traceback (most recent call last):