Multimap store elements in key value pair. It can also have duplicate keys.

There can be many scenarios when we want to find all the values associated with a key in multimap.

For example, we have a multimap of char & int as key value pair and initialzed with following values i.e.

There are 3 pairs with duplicate key ‘c’. Values associated with key ‘c’ are 3,5 & 6. Now let’s see how to access all the values associated with a key in multimap.

std::multimap::equal_range

We can find all values of a key in Multimap using is member function equal_range().

It accepts the key as an argument and returns a pair of multimap iterator. This returned pair has a range that represents the entries with given key.

Let’s see an example,

Output:

To compile the above code in Linux use following command,

g++ –std=c++11 example.cpp

How to find if a key exists or not in multimap with equal_range()

As equal_range() returns a range representing all the elements with given key. So, to check if a key exists or not, we will calculate the total number of elements in given range of iterators. It can be done using std::distance() algorithm i.e.

If the count is 0 i.e. no elements in range thenit means key don’t exists in multimap.

Checkout the example as follows,

 

Output:

To compile the above code in Linux use following command,

g++ –std=c++11 example.cpp

Python Resources

C++11 / C++14 Resources

Design Patterns Resources

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.

Do Subscribe with us for more Articles / Tutorials like this,