Sequential memory sequence container (vector, string, deque)
For continuous memory sequence STL containers, such as vector,string,deque, deleting the current iterator will invalidate all subsequent iterator because they use contiguous allocated memory, and deleting an element causes all subsequent elements to move forward one position. ensure continuity of elements. When the erase method of the above container can return the next valid iterator, that is, the returned iterator of the erase method points to the valid iterator of the element immediately following the deleted element, so that the subsequent element can continue to be accessed based on this return value.
Example of a continuous memory sequence container to delete a specific element:
vector<int> VC; for (vector<int>::iterator It! = Vc.begin (); It! = Vc.end ();) { if(Need_delete ()) it = vc.erase (it); Else ++it;}
Associative containers (set, Multiset, map, Multimap)
For the associative container, delete the element that the current iterator points to, just make the current iterator invalid, as long as erase, increment the current iterator, get the next element iterator. Just because of the association container such as map, using the red black tree implementation, inserting, deleting a node will not affect the other nodes. The erase method of the associated container cannot return the next valid iterator (c++98), the deleted iterator fails, all must be ensured that the next iterator is available before deleting the current element, and the "post-increment iterator" technique can be used.
Example of a specific element deleted by the associated container:
map<int,int> m; for (map<int,int>::iterator it = M.begin (); it!= m.end ();) { if(Need_delete ()) m.erase (it++); Else ++it; }
Because the IT parameter passed to the erase method is a copy of the iterator, it++ points to the next element, so erase gets the current iterator, it already has + + on the inside of the erase, and points to the next iterator, just to meet the need.
Non-contiguous Memory sequence container (list)
For list, it uses discontinuous memory, and its erase method returns the next valid iterator, so both of the methods used to delete a particular element are available.
Failure analysis of STL container iterator