Erase has two prototype types: delete a node and segment. For vector and list, the Operation definition is the same.
template< class _TYPE, class _A> iterator vector::erase(iterator Iterator );
- Check the source code of STL. The iterator returned by this function points to the next valid node (if not, it points to end)
- Note that this definition cannot be used to call it ++ in the for loop. Otherwise, it is equivalent to "It + = 2 ″. if you want to traverse the data in a loop correctly, you must process the returned values of erase, because it points to a destroyed value after list: erase (iterator it) is called, when it ++ is called, the memory becomes abnormal.
- Although vector does not have such a problem, it will also have an error at the boundary.
- Correct Processing is simple
iterator _Last = end(); for (iterator _First = begin(); _First != _Last; ){ if (*_First == _Val) _First = erase(_First); else ++_First; }
Another one:
Print the deleted items except all the even items.
1. Vector/queue
Method 1:
Void erase (vector <int> & V)
{
For (vector <int>: iterator Vi = V. Begin (); vi! = V. End ();)
{
If (* Vi % 2 = 0)
{
Cout <"erasing" <* VI <Endl;
Vi = V. Erase (VI );
}
Else ++ VI;
}
}
Method 2:
Void erase2 (vector <int> & V)
{
For (vector <int >:: reverse_iterator rI = V. rbegin (); Ri! = V. rend ();)
{
If (* Ri % 2 = 0)
{
Cout <"erasing" <* RI <Endl;
V. Erase (++ RI). Base (); // The erase () function expects forward iterator.
// Use the base () function to convert reverse iterator to forward
}
Else ++ Ri;
}
}
2. MAP/List
Correct Method
Void erase (Map <int, int> & M)
{
For (Map <int, int >:: iterator MI = M. Begin (); Mi! = M. End ();)
{
If (mi-> second % 2 = 0)
{
Cout <"erasing" <mi-> second <Endl;
M. Erase (MI ++ );
}
Else ++ Mi;
}
}
Other two:
Containers in STL are divided into two types by storage method: containers stored in arrays (such as vector and deque), and containers stored in discontinuous nodes (such: list, set, map ). When using the erase method to delete elements, pay attention to some issues.
When using list, set, or map traversal to delete some elements, you can use the following method:
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 ++;
}
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 ++;
}
Note: vector and deque cannot be traversed and deleted in the "correct method 2" method above.