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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! A range based for is an iterator?
@Cincinnatus The range-based for loop uses an internal iterator that gets incremented in each iteration. See here: en.cppreference.com/w/cpp/language/range-for