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 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.

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

Ouput:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.