Previously found in vector erase method is somewhat strange (^_^), a little attention, will be wrong. Once again today, it is simply summed up, especially in the circulation body with erase, because Vector.begin () and Vector.end () are changed, so the possibility of error is introduced.
There are two types of erase function prototypes:
Iterator Erase (iterator position);
Iterator Erase (iterator first, iterator last);
Vector<int> Veci;
Veci.push_back (1);
Veci.push_back (2);
Veci.push_back (3);
Veci.push_back (4);
Veci.push_back (5);
Veci.push_back (3);
Veci.push_back (2);
Veci.push_back (3);
For (Vector<int>::iterator Iter=veci.begin (); Iter!=veci.end (); iter++)
{
if (*iter = = 3)
Veci.erase (ITER);
}
At first glance this piece of code is normal. In fact, there is a very serious error in this area: when Veci.erase (ITER), ITER becomes a wild pointer, iter++ to a wild pointer is sure to go wrong.
Viewing MSDN, the return value for erase is described in this way: an iterator that designates the first element remaining beyond any elements removed, or a pointer To the end of the vector if no such element exists, then change the code:
For (Vector<int>::iterator Iter=veci.begin (); Iter!=veci.end (); iter++)
{
if (*iter = = 3)
iter = Veci.erase (ITER);
}
This code is also wrong: 1) cannot delete two consecutive "3", 2) when 3 is at the last position of the vector, it will also error (execute + + operation on Veci.end ())
The correct code should be:
For (Vector<int>::iterator Iter=veci.begin (); Iter!=veci.end ();)
{
if (*iter = = 3)
iter = Veci.erase (ITER);
Else
ITER + +;
}
To avoid manipulation of the wild pointer, another workaround is as follows:
Vector<int>::iterator Itor2;
For (Vector<int>::iterator Iter=veci.begin (); Iter!=veci.end ();)
{
if (*iter = = 3)
{
Itor2=iter;
Veci.erase (ITOR2);
}
Else
ITER + +;
}
Another way to resolve the inability to delete two contiguous 3 is as follows:
Vector<int> Veci;
Veci.erase (Remove (Veci.begin (), Veci.end (), 6), Veci.end ());
The Remove () function is used here.
Note: Remove is a generic algorithm for STL std::remove (First,last,val) removes [first, last] the element that is equal to Val in the vector is similar to iter = Std::remove (vec.begin (), Vec.end (), Val) but this function simply moves Val to the end of the VEC, and does not really delete or call the erase function once
Internship Small white:: (turn) vector in erase usage precautions