C++ Program to Implement Multimap in STL


Multimap is similar to map with an exception that multiple elements can have same keys. The key value and mapped value pair has to be unique in multimap.

Function is used here -

  • mm::find() – Returns an iterator to the element with key value ‘b’ in the multimap if found, else returns the iterator to end.

  • mm::erase() – Removes the key value from the multimap.

  • mm:: equal_range() – Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to key.

  • mm insert() – To insert elements in the multimap container.

  • mm size() – Returns the number of elements in the multimap container.

Example Code

#include<iostream>
#include <map>
#include <string>
using namespace std;
int main () {
   multimap<char, int> mm;
   multimap<char, int>::iterator it;
   mm.insert (pair<char, int>('a', 10));
   mm.insert (pair<char, int>('b', 20));
   mm.insert (pair<char, int>('b', 30));
   mm.insert (pair<char, int>('a', 40));
   cout<<"Size of the multimap: "<< mm.size() <<endl;
   cout << "Multimap contains:\n";
   for (it = mm.begin(); it != mm.end(); ++it)
      cout << (*it).first << " => " << (*it).second << '\n';
   for (char c = 'a'; c <= 'b'; c++) {
      cout << "There are " << mm.count(c) << " elements with key " << c << ":";
      multimap<char, int>::iterator it;
      for (it = mm.equal_range(c).first; it != mm.equal_range(c).second; ++it)
         cout << ' ' << (*it).second;
         cout << endl;
   }
   it = mm.find('b');
   mm.erase (it);
   cout<<"Size of the multimap: "<<mm.size()<<endl;
   cout << "Multimap contains:\n";
   for (it = mm.begin(); it != mm.end(); ++it)
      cout << (*it).first << " => " << (*it).second << '\n';
   return 0;
}

Output

Size of the multimap: 4
Multimap contains:
a => 10
a => 40
b => 20
b => 30
There are 2 elements with key a: 10 40
There are 2 elements with key b: 20 30
Size of the multimap: 3
Multimap contains:
a => 10
a => 40
b => 30

Updated on: 30-Jul-2019

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements