Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent rehashing of an std::unordered_map while removing elements?

Tags:

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?

like image 958
vmrob Avatar asked Dec 05 '12 18:12

vmrob


1 Answers

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.

like image 174
Howard Hinnant Avatar answered Sep 22 '22 08:09

Howard Hinnant