Containers are very convenient and often used to store more than one piece of data, and then the data can be deleted and modified.
Sometimes you want to delete a piece of data while traversing, but the program causes the program to crash when you delete it.
This problem does not occur in GCC, and is available in vs2008,vs2010, and other higher vs versions are not tested.
such as the map container:
map<int,string>DataMap; for(inti =0; I <Ten; ++i) {Datamap.insert (Datamap.end (), Make_pair (i,string("Str")));} Map<int,string>::iterator iter =Datamap.begin (); while(ITER! =Datamap.end ()) {if(Iter->first = =3) {datamap.erase (ITER); } ++iter;}
A debug assertion is raised when printing to 3str failed!
This is because the ITER has pointed to an invalid address after the use of erase to remove ITER, and then the next round of the loop while condition is established, then the program will collapse when using Iter->first.
And look at the vector.
vector<int> dataVec; for (int0; + +i) { datavec.push_back (i);} Vector<int>::iterator iter = datavec.begin (); while (iter! = Datavec.end ()) {if (3 = = *iter) { datavec.erase (ITER); } + +iter;}
will also collapse.
The same is true for other container list,deque,set,multiset,multimap.
I think the more straightforward way is to delete the ITER of the next pointer to temporarily save a copy, erase and then re-assigned to the ITER, continue the next round of circulation.
vector<int>::iterator iter = datavec.begin (); vector<int>:: Iterator Tempiter; while (iter! = datavec.end ()) {if (5 = = *iter ) {1; Datavec.erase (ITER); = tempiter; } else { + +iter;
}}
But this still will collapse, helpless had to put the erase call in the loop outside, detect to delete the ITER temporary record a copy, Traverse end and then delete.
vector<int>::iterator iter = datavec.begin (); vector<int>:: Iterator Tempiter; while (iter! = datavec.end ()) {<< *iter << Endl ; if (5 = = *iter) {= iter ; } + +iter;} Datavec.erase (tempiter);
This ensures that no further crashes are possible.
Removal of C + + containers during traversal