2

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?

3 Answers3

6

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.)

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
3

you may want to reassign your iterator when you erase an element, as it wont be valid otherwise...

it = mymap.erase(...)
rmp
  • 1,053
  • 7
  • 15
2

To avoid using the iterator after invalidating it when erasing, the loop body should be like this:

if (should_erase) {
    it = my_map.erase(it); // C++11: returns the next iterator
    my_map.erase(it++);    // Historic C++: no helpful return value
} else {
    ++it;
}
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644