Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ loop through map while erasing [duplicate]

Tags:

c++

To loop through a map in c++ we do sth like this

map<string,int> mymap;
map<string,int>::iterator it= mymap.begin();
while(it!=mymap.end()) {
   //code here
   it++;
}

What if in the "code here" part i have an if statement that if evaluated to true, it erases one element from the map? How should my code change so that it still loops through all mymap elements in order?


1 Answers

http://en.cppreference.com/w/cpp/container/map/erase :

References and iterators to the erased elements are invalidated. Other references and iterators are not affected.

(So make sure you increment and save a "next" iterator before you erase.

Edit: In fact since C++11, erase returns the next iterator anyway, so you may use that.)

like image 126
BoBTFish Avatar answered Mar 27 '26 00:03

BoBTFish