This post will discuss how to remove entries from a map while iterating it in C++.

The idea is to iterate the map using iterators and call the unordered_map::erase function on the iterators that match the predicate. Since calling the erase() function invalidates the iterator, we can use the return value of erase() to set the iterator to the next element in the sequence.

Download  Run Code

Output:

{C++, C++17}
{C, C99}

 
The above approach won’t work before C++11 as the erase() function doesn’t return anything in C++98/03. The workaround is to post-increment the iterator while passing to the erase() function. This increments the iterator before it is invalidated by the erase() function and can be used in the next iteration of the loop.

Download  Run Code

 
Another feasible solution that works exactly like the previous approach is to make an explicit copy of the iterator increment it and call the erase() function on the copy.

Download  Run Code

 
We can also maintain a ‘to-be-removed-list’ of iterators to entries that satisfy the predicate. Then we loop through that list and call set::erase on each iterator.

Download  Run Code

That’s all about removing entries from a map while iterating it in C++.