Code:
for(iter=vec.begin(); iter!=vec.end();iter++)
iter = vec.erase(iter);
is equivalent to:
Code:
iter = vec.begin();
while (iter != vec.end())
{
iter = vec.erase(iter);
iter++;
}
Let's see what happens with one item in the vector:
Code:
iter = vec.begin();
while (iter != vec.end())
{
iter = vec.erase(iter); /* Returns vec.end() */
iter++; /* Moves to vec.end() + 1 */
/* Loop will not stop as we are at vec.end() + 1, therefore we will crash. */
}
and with two items:
Code:
iter = vec.begin();
while (iter != vec.end())
{
iter = vec.erase(iter); /* Returns vec.end() - 1 (second item in vec) */
iter++; /* Moves to vec.end() */
/* Loop will stop as we are at vec.end(), but not every item will be deleted. */
}
In fact, the code will crash with if vec has an odd number of items and not crash if vec has an even number of items.