Consider this piece of code:
#include <vector>
#include <iostream>
int main(int argc, char** args)
{
std::vector<int> vec;
vec.push_back(0);
for (auto iter = vec.begin(); iter != vec.end(); iter++)
{
vec.push_back((*iter) + 1);
std::cout << *iter << std::endl;
}
}
I expected this to print all the numbers to Infinite. But what it did was to print a LOT of zeros (and an occasional -256, WHAT?) only to run into a segfault.
My assumtion is that iter
still points to the old array after the call to vec.push_back
moves the internal data to a new array.
What exactly is the problem here? Is my assumption correct, that the push_back
call invalidates the iterator?
Interestingly, when I substitute std::vector for a std::list, the code works as expected. Is it save to use a std::list instead? Or is that just working correctly by accident?