It is well known that when iterating through an STL container using an iterator, special attention needs to be paid to whether the iterator is modified in the loop and causes the iterator to fail. Let me conclude by summarizing the use of iterators correctly when deleting elements in forward and backward traversal of various containers. This article complete source code: https://code.csdn.net/snippets/173595
First, it's a good idea to understand that using forward iterators (iterator) for backward traversal is a bad use, or why you have a reverse iterator (reverse_iterator). Secondly, depending on the characteristics of the container, the use of traversal deletes can be divided into two groups, the first group is list and vector, and the second group is map and set.
Next, look at how the specific usage.
First scenario: Forward traversal Delete element
For lists and vectors, their erase function returns the next iterator, so that when traversing, only it = c.erase (it) is required; Can.
For map and set, their erase function returns void, and after erase, the current iterator is invalidated and cannot be used to get the next iterator. So before you need to erase, you get an iterator that points to the next element. Such as:
Tmpit = it;
++it;
C.erase (Tmpit);
The three lines of code on the suffix + + operator (first creating a replica, then incrementing the iterator, and then returning a copy) can be reduced to one line:
C.erase (it++);
Here's a look at the example:
List forward Traversal delete element sample (same vector usage):
Erase with iterator
list<int>::iterator it;
for (it = L.begin (); it!= l.end ();)
{
if (0 = (*it)% 2) {
it = l.erase (it);
}
else {
++it;
}
}
Map Forward Traversal delete element sample (same set usage):
Erase with iterator
Map<int, int>::iterator mit;
for (mit = M.begin (); MIT!= m.end ();)
{
if (0 = = Mit->first% 2) {
m.erase (mit++);
}
else {
++mit;
}
}