The map in C + + STL is very common. Usually we traverse in the following way and delete some entry in the map:
map <int , int ; Mp;mp.insert ( Make_pair (1 , 1 )); Mp.insert (Make_pair (2 , 3 ); //insert some elements for (map <int , int ; :: Iterator iter = Mp.begin (); Iter! = Mp.end (); iter++) {if (Iter->first = = 1 ) mp.erase (ITER) ; //NOTE it is not safe! else iter->second++;}
The above removal is not safe because the structure of ITER has changed since Mp.erase (ITER), and the iter++ of the For loop sheet may be problematic. The following modifications are therefore recommended:
for (map<int, int>::iterator iter = mp.begin(); iter != mp.end(); ) { if1// NOTE it is SAFE! else iter->second++;}
The deletion is safe here, because ITER will cache it before it is deleted, and then pass it on to erase to delete it. The iter++ was therefore carried out on the basis of the original ITER. This approach is also recommended in C + + documentation.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"C + +" Map Iterator removal example