Erase () trap of STL-iterator failure summary, stlerase
The following materials are collected from Internet & books.
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.
1. list, set, map container
When using list, set, or map traversal to delete some elements, you can use the following method:
1.1 correct syntax 1
1 std::list< int> List; 2 std::list< int>::iterator itList; 3 for( itList = List.begin(); itList != List.end(); ) 4 { 5 if( WillDelete( *itList) ) 6 { 7 itList = List.erase( itList); 8 } 9 else10 itList++;11 }
1.2 correct syntax 2
1 std::list< int> List; 2 std::list< int>::iterator itList; 3 for( itList = List.begin(); itList != List.end(); ) 4 { 5 if( WillDelete( *itList) ) 6 { 7 List.erase( itList++); 8 } 9 else10 itList++;11 }
1.3 incorrect syntax 1
1 std::list< int> List;2 std::list< int>::iterator itList;3 for( itList = List.begin(); itList != List.end(); itList++)4 {5 if( WillDelete( *itList) )6 {7 List.erase( itList);8 }9 }
1.4 incorrect syntax 2
1 std::list< int> List; 2 std::list< int>::iterator itList; 3 for( itList = List.begin(); itList != List.end(); ) 4 { 5 if( WillDelete( *itList) ) 6 { 7 itList = List.erase( ++itList); 8 } 9 else10 itList++;11 }
1.5 Analysis
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.
2. vector, deque container
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:
2.1 correct writing
1 std::vector< int> Vec; 2 std::vector< int>::iterator itVec; 3 for( itVec = Vec.begin(); itVec != Vec.end(); ) 4 { 5 if( WillDelete( *itVec) ) 6 { 7 itVec = Vec.erase( itVec); 8 } 9 else10 itList++;11 }