It is obvious for many that this code will produce a segment fault.
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<int> ints;
ints.push_back(5);
std::vector<int>::iterator it;
for(it = ints.begin(); it != ints.end(); ++it){
std::cout << *it;
it = ints.erase(it);
}
}
If we remove the ++it
and add a condition to erase, we can avoid this error. But what is the actual cause of the issue? In our loop we say, for the start of the iterator, until it reaches the end, incrementing by one, print out the value and then erase it. Is it because the ++it
is called at the "end" when, in this condition, we've already removed the next (only) value?