Failure of STL iterator
Containers in STL are divided into two types by storage method. One is the sequential containers (such as vector and deque) stored in arrays ); another type of containers are stored in the form of discontinuous nodes (such as list, set, and map ). When using the erase method to delete elements, pay attention to some issues.
1. Use an unordered container to traverse and delete (list, set, map)
When using list, set, or map traversal to delete some elements, you can use the following method:
Method 1
STD: List list;
STD: List :: iterator itlist;
for (itlist = List. begin (); itlist! = List. end ();)
{< br> If (willdelete (* itlist)
{< br> itlist = List. erase (itlist);
}< br> else
itlist ++;
}< br>
Or
Correct method 2
STD: List <int> list;
STD: List <int >:: iterator itlist;
For (itlist = List. Begin (); itlist! = List. End ();)
{
If (willdelete (* itlist ))
{
List. Erase ( Itlist ++ );
}
Else
Itlist ++;
}
The following are two incorrect usage methods:
Error Method 1
STD: List <int> list;
STD: List <int >:: iterator itlist;
For (itlist = List. Begin (); itlist! = List. End (); itlist ++)
{
If (willdelete (* itlist ))
{
List. Erase (itlist );
}
}
Or
error method 2
STD: List list;
STD: List :: iterator itlist;
for (itlist = List. begin (); itlist! = List. end ();)
{< br> If (willdelete (* itlist)
{< br> itlist = List. erase (++ itlist);
}< br> else
itlist ++;
}< br>
Correct Method 1: Obtain the location of the next element through the returned values of the erase Method
Correct Method 2: Use "++" to obtain the location of the next element before calling the erase method.
Incorrect Method 1: After the erase method is called, "++" is used to obtain the location of the next element. Because the element location has been deleted after the erase method is called, if you obtain the next location based on the old location, an exception occurs.
Error Method 2: Same as above.
Here, the "++" operator is the opposite of our normal understanding. Erase (itlist ++) first obtains the location of the next element and deletes it; erase (++ itlist) is the location of the next element after deletion.
2. Use a sequential container to traverse and delete (vector, deque)
When you use vector and deque to traverse and delete elements, you can also obtain the position of the next element through the returned values of erase:
Correct usage
STD: vector VEC;
STD: vector : iterator itvec;
for (itvec = Vec. begin (); itvec! = Vec. end ();)
{< br> If (willdelete (* itvec)
{< br> itvec = Vec. erase (itvec);
}< br> else
itlist ++;
}
note: vector and deque cannot traverse and delete objects in the "correct method 2" method above.