In this article we will discuss two different ways to erase elements from map i.e.

In previous article we discussed how to erase elements by key and iterator using member function std::map::erase. But there is no default function to delete elements by value instead of key or delete elements based on callback.

We will create generic erase_if for std::map

Erasing elements by value

Algorithm Used

Iterate over all the elements and delete the elements(Key-value pairs) whose value field matches the given value.

We will create a template function that can work with all kind of map i.e. std::map<K, V> where K & V can be anything.

Complete example is as follows,

Output:

Erasing elements by Callback

Algorithm Used

Iterate over all the elements and execute given callback with each element. It callback returns true then delete that element and move to next.

We will create a template function that can work with all kind of map i.e. std::map<K, V> where K & V can be anything.

Example:

Suppose we have a map of string and int. Delete all elements whose value is Odd

Complete example is as follows,

Output:

 

 

 

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