I have an std::unordered_map that I will be removing elements from via iteration.
auto itr = myMap.begin(); while (itr != myMap.end()) { if (/* removal condition */) { itr = myMap.erase(itr); } else { ++itr; } }
I would like to prevent the map for performing any expensive operations until I'm done removing all of the elements that I need to remove. Do I have a valid concern? Am I misunderstanding how the internal storage works?
The unordered containers are forbidden from rehashing during an erase
:
[unord.req]/p14:
The
erase
members shall invalidate only iterators and references to the erased elements, and preserve the relative order of the elements that are not erased.
[unord.req]/p9:
Rehashing invalidates iterators, changes ordering between elements, and ...
Your code is fine as is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With