Consider the canonical algorithm for removing an element from an associative container while iterating:
for (auto iter = myMap.begin(); iter != myMap.end(); )
{
if (/* removal condition */)
{
iter = myMap.erase(iter);
}
else
{
++iter;
}
}
I've been applying this algorithm without a second thought when using the C++11 std::unordered_map
container. However, after browsing the documentation for std::unordered_map::erase
on cppreference.com, I became a little concerned after reading the following note:
The order of the elements that are not erased is preserved (this makes it possible to erase individual elements while iterating through the container) (since C++14)
Based on this statement, I'm assuming there was language added to the C++14 standard to ensure library implementers guarantee ordering after a call to std::unordered_map::erase
. For example, maybe such a requirement constrains the implementation from not rehashing the entire container after an element is removed, but rather only allows it to remove the element from its corresponding bucket?
Without such a guarantee in C++11, and if I desire my code to be portable, do I have to worry that some elements will be visited multiple times or not at all if I remove an element from an std::unordered_map
during iteration?