When we use the erase (iterator it) method of map to delete elements, if erase is in the Code for traversing the map, we need to be careful when calling erase. Erase will invalidate the input parameter iterator and affect the subsequent it ++ logic for traversing the map.
The simple method is to save the it to be deleted, point it used to traverse the map to the next location, and delete the saved it. As shown in the following code:
# Include <map>
# Include <iostream>
Using namespace STD;
Int main ()
{
Map <int, int> map1;
Map <int, int >:: iterator mapit;
Map <int, int >:: iterator saveit;
Map1 [1] = 2;
Map1 [2] = 3;
Map1 [3] = 4;
Map1 [4] = 5;
Mapit = map1.begin ();
While (mapit! = Map1.end ()){
Cout <"element key:" <mapit-> first <", value:" <mapit-> second <Endl;
If (mapit-> first = 2 ){
Saveit = mapit;
Mapit ++;
Map1.erase (saveit );
Continue;
}
Mapit ++;
}
Cout <"map size:" <map1.size () <Endl;
Return 0;
}
Note that Windows STL (STL in Windows C ++ compiler) is different from Linux STL (STL in GCC.
In Windows STL, the erase method of map will return an iterator, which points to the iterator after the currently deleted iterator, so in this case, you only need to assign the iterator used for loop to the return value of the erase function. Refer to the above Code as follows:
Mapit = map1.erase (mapit); then you can continue.
However, writing code in Linux cannot be compiled.