5

I often use this syntax to loop through a std::map:

for( const auto& my_pair: my_map )

Can I call my_map.erase( my_pair.first ); safely?

  • [*References and iterators to the erased elements are invalidated. Other references and iterators are not affected.*](http://en.cppreference.com/w/cpp/container/map/erase) – chris Aug 11 '14 at 15:31

1 Answers1

6

No, it is not safe.

my_map.erase( my_pair.first );

Here you're calling erase with a key value, meaning that you will remove all elements with that key value.

When erasing elements from a std::map this applies:

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

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

Therefore, it is unsafe to increment the current iterator as it may have been invalidated.

Felix Glas
  • 15,065
  • 7
  • 53
  • 82
  • Thank you! A range based for is an iterator? –  Aug 11 '14 at 16:05
  • 2
    @Cincinnatus The range-based for loop uses an internal iterator that gets incremented in each iteration. See here: http://en.cppreference.com/w/cpp/language/range-for – Felix Glas Aug 11 '14 at 16:08