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