In this article we will discuss the MultiMap in C++.

Multi-map in C++ is an associative container like map. It internally store elements in key value pair. But unlike map which store only unique keys, multimap can have duplicate keys.

Also, it internally keep elements in sorted order of keys. By default it uses < operator to compare the keys.

MultiMap Usage Scenario

Let’s discuss a practical scenario, where we should use multi-map. Suppose, given a string and we want to store the position of each character in that string. For example, String is “this is it” and position of each character in string is,

t occurs at 0 , 9
h occurs at 1
i occurs at 2 , 5 , 8
s occurs at 3 , 6

Here key is ‘char’ and value is ‘int’ i.e. position of character in string. So, there are multiple key value pairs with duplicate keys. Therefore, we will use multi-map to store this elements because in multi-map we can have duplicate keys. MultiMap will store the above data in following  key value pairs i.e.

It will have duplicate keys and elements will be sorted based on keys.

Declaring a Multi-Map in C++

Let’s create a multi-map of char & int i.e.

We need to include following header file for it,

Initializing a MultiMap with C++11 Initializer list

Let’s initialize this multimap with initializer list i.e.

Inserting a key value pair in MultiMap

We can also insert a key value pair in multimap using insert() member function i.e.

Iterating over the Multi-Map using Iterator

Iterating over the MultiMap using C++11 Range Based for loop

Complete Example

Complete example of Muli Map in C++ is as follows,


To compile the above code in lunux use following command,

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

In the next article we will discuss how to find all values associated with a key in multimap i.e.

Find All values associated with a Key in MultiMap using equal_range()

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.