Self-sensing, the erase function returns an iterator that points to the next position of the deleted element, not very reasonable.
Do not say anything, directly on the code:
int findnum = 2;
int array[] = {1, 2, 2, 4, 5, 6};
Vector<int> Ivec (array, array + sizeof (array)/sizeof (*array));
for (Vector<int>::iterator iter = Ivec.begin (); I! = Ivec.end (), iter++)
{
if (*iter = = FindNum)
{
iter = Ivec.erase (ITER);
Continue
}
Else
{ }
}
This code, seemingly no problem, in fact, ITER after the re-assignment, and then again + +, will skip an element, in this case, the third element 2 will be skipped.
Change the conditions, the element to be looked up from 2 to 6 what happens, the dead loop or direct collapse, in which the reason is self-evident, continue after the ITER is equal to end (), and then again + +, will point to end () position, this position is illegal.
The first step, before continue, plus iter--
Just half, try to change the search element to 1, what will happen, iter--will collapse.
Therefore, there is a need to add a judgment:
if (iter! = Ivec.begin ()) iter--;
This problem can also be used to move the FOR loop increment statement iter++ from the head to the loop body and the + + operation in else.
Erase function call problem in STL container