The containers in the STL are stored in two categories, one for containers that are stored as arrays (e.g. vectors, deque), and those that are stored in discontinuous nodes (for example, list, set, map). There are some issues to be aware of when using the Erase method to remove elements.
You can use this when you use list, set, or map traversal to delete certain elements:
correct use of Method 1:
std::list< int> list;
std::list< Int>::iterator itlist;
for (itlist = List.begin (); Itlist! = List.end ();)
{
if ( willdelete ( *itlist))
{
itlist = List.erase (itlist);
}
else
itList++;
}
Correct use 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++;
}
here are two ways to use the error:
std::list< int> list;
std::list< Int>::iterator itlist;
for (itlist = List.begin (); Itlist! = List.end (); itlist++)
{
if (Willdelete (*itlist))
{
List.erase (itlist);
}
}
std::list< int> list;
std::list< Int>::iterator itlist;
for (itlist = List.begin (); Itlist! = List.end ();)
{
if (Willdelete (*itlist))
{
Itlist = List.erase (++itlist);
}
Else
itlist++;
}
Correct use Method 1: Get the position of the next element by the return value of the Erase method
Method 2: Use "+ +" to get the position of the next element before calling the Erase method
Error using Method 1: Use "+ +" after calling the erase method to get the position of the next element, because the position of the element has been deleted after the erase method is called, and an exception occurs if the next position is obtained from this old location.
Error using Method 2: Ibid.
The "+ +" operator here is exactly the opposite of what we normally understand, erase (itlist++) is the position at which the next element is first fetched, and erase (++itlist) is the position at which the next element is deleted.
C + + List erase ()