In this article will discuss how to search for all the elements in map with given value.

Map internally store elements in Key-Value pair. In which keys are unique but values can be duplicate. There are member functions to search pairs by key i.e. std::map::find(). But there is no direct function to search for all the elements with given value.

Suppose we have map of string & int i.e.

Now we want to find all the elements with value 6 i.e.

at :: 6
is :: 6

To do this we need to create a customized function.

Algorithm Used:

As there is no direct function so, we need to iterate over all the elements and check the value of each element. If value matches the given value then add them to the list.

Let’s create a generic function for it i.e.

It accepts a vector of key type by reference, the map to search and the value to look for. Then it pushes all the keys with given value in the vector.

Let’s call this function to search for all the pairs with value 6 i.e.

Complete example is as follows,



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.