Vector::erase cancels iterators for all elements after the first element that has been deleted. This makes sense since the vector stores its data in an array. When an element is deleted, all elements after it should be shifted along, for example.
int test[] = {0, 1, 2, 3, 4, 5}; ^
In the above example, we have an iterator pointing to the value 5 that we want, however element 1 is erased, now we have:
0, 2, 3, 4, 5 ^
An iterator points to the end of the array, the problem.
With std::map data is stored in a binary tree, so when an element is erased, the pointers on the left and right of some nodes change, but their location in memory does not change. As a result, all existing iterators pointing to elements that have been erased remain valid.
source share