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

Advertisements

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
			it++;
	}

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

	return 1;
}

Ouput:
Second :: 2
Third :: 3

 

 

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

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

Scroll to Top