Erase in the loop:
(1) For an associative container, nothing is returned after erase, and subsequent iterators cannot be down, that is, you cannot perform ++it or it--operations. What needs to be done is to it++ the iterator when it is deleted, so that it is OK to go down.
(2) For a sequence container, the next iterator is returned after erase, but causes all subsequent iterators to fail, and if you want the loop to continue, save the return value of the iterator and start the iteration here.
Regardless of the container, the regular three-segment for () is no longer applicable.
In c++11, Erase returns the next iterator, but the previous version returns void. Erase was poorly designed, making it easier for the person to make a mistake. Defective c++!.
void Erase( iterator pos); |
|
(Until c++11) |
Iterator Erase( const_iterator pos); |
|
(Since c++11) |
void Erase( iterator first, iterator last); |
|
(Until c++11) |
Iterator Erase( const_iterator First, const_iterator last); |
|
(Since c++11) |
However, many compilers currently do not support c++11, or are only partially supported. So it's best to use the surest way to write it++ out of the loop.
(1) Associative container (take map for example)
For (It=map.begin (); It! = Map.end (); )
{
if (CanDelete (IT))map.erase (it + +); In c++11, you can write only map.erase (it), but first confirm that your compiler supports C++11, such as g++ 4.7.3.
else ++it;
}
(2) Sequence container (take vector as an example)
for (it = Vector.begin (); It! = Vector.end ();)
{
if (CanDelete (it)) it = vector.erase (it); To keep the returned value in it, it will be in an invalid state, and then the ++it will be meaningless. C++11 Associative containers can also be written like this
else + + it;
}
Erase-induced iterator Failure Analysis (C++11)