In this article we will discuss the different ways to remove an element from an unordered_map.

Unordered_map provides different overloaded version of erase() member function to delete key value pairs from map.

Erasing an element from an unordered_map by key

Unordered_map provides following overloaded version of erase() that accepts a key by value and check if any element with given key exists and if yes then deletes that element.

It returns the number of elements deleted. But as unordered_map can conain only unique elements, so it will return either 0 or 1.

Lets see an example,


Erasing an element from an unordered_map through an iterator

Unordered_map also provides an overloaded version of erase() that accepts an iterator an deletes it i.e.

It accepts an iterator and deletes the corresponding element. Also, it returns the iterator pointing to an element i.e. next to last deleted element.

Let’s see an example, where it searches for an element with key “Fourth” and then deletes that using iterator,


In the above output entry with key “Fourth” is not present because that’s deleted.

Erasing an element by value from an unordered_map

Unordered_map store values in a key value pair and erase() function of unordered_map can take either iterator or key.

So, to delete an element by value we need to, iterate over all the elements in map and search for element whose value matches the given value. Then  we will use its iterator to delete that element.

Let’s see an example, it searches for an element with value 2 and then deletes that element i.e.



Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.