c++11 unordered_map : erase elements while iterating in a loop

In this article we will discuss how to erase multiple elements from an unordered_map based on some condition and while iterating.

Erasing Multiple elements from unordered_map while iterating

Suppose we have an unordered_map of string and integers as key value pairs i.e.

  • First : 1
  • Second : 2
  • Third : 3
  • Fourth :  4
  • Fifth : 5

Now, we want to delete all elements whose key starts with letter ‘F’ . So, to delete all those elements we need to iterate over the map to find those elements. Therefore, we want to delete all those elements in a single iteration.

To delete an element using iterator we will use erase() function of unordered_map that accepts an iterator and deletes that element i.e.

iterator erase ( const_iterator position );

Iterator Invalidation

But after erasing the element this iterator “position” will become invalid. Then how will we go to next element in loop ?

To avoid this problem erase() function returns an iterator to next element of the last deleted element. We will use it i.e.

it = wordMap.erase(it);

Checkout the following example, here we will delete all elements whose key starts with letter ‘F’ in single iteration,

#include <iostream>
#include <unordered_map>
#include <string>

int main() {
	// Initialize an unordered_map through initializer_list
	std::unordered_map<std::string, int> wordMap( { { "First", 1 }, { "Second",
			2 }, { "Third", 3 }, { "Fourth", 4 }, { "Fifth", 5 } });

	// Iterator pointing to first element in map
	std::unordered_map<std::string, int>::iterator it = wordMap.begin();

	// Erase all element whose key starts with letter 'F' in an iteration
	while (it != wordMap.end()) {
		// Check if key's first character is F
		if (it->first[0] == 'F') {
			// erase() function returns the iterator of the next
			// to last deleted element.
			it = wordMap.erase(it);
		} else

	for (auto element : wordMap)
		std::cout << element.first << " :: " << element.second << std::endl;

	return 1;


Second :: 2
Third :: 3



Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top