Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

what
multimap
c++

What is a multimap in C++?

Educative Answers Team

A multimap can store more than one value against a key. Both keys and values are stored in the form of a tuple. A multimap is similar to a map in C+; the only difference is that a multimap can hold keys that are not unique (unlike in a standard map). See the example below of how to insert a pair into myMap <int,char> and myMultimap <int, char>.

The following code is used to insert the pair in the map:


myMap.insert(pair <int, char>
(1, 'a'));
//This will assign 1 as a key and 
//'a' as a value

//WE CANNOT DO THE 
//FOLLOWING IN MAPS

myMap.insert(pair <int, char> 
(1, 'e')); //Will give error

//Since it is important for 
//a single key to have 
//a single value

However, in a multimap, a user can assign two values to a single key:​

myMultimap.insert(pair <int, char>
(1, 'a'));
//This will assign 1 as a key and 
//'a' as a value

myMap.insert(pair <int, char> 
(1, 'e')); //Assigned 'e' to
//key 1

//Now Key 1 looks like
// 1 --> a
// 1 --> b 

Idea illustration

The following illustration explains this concept better:

svg viewer
Adding values in a Multimap indirectly

Code

The code snippet below implements the illustration above​:

#include <iostream> 
#include <map> 
#include <iterator> 
  
using namespace std; 
  
int main() 
{ 
    multimap <int, char> gquiz1;        // empty multimap container 
  
    // insert elements in random order 
    gquiz1.insert(pair <int, int> (1, 'a')); 
    /*gquiz1.insert(pair <int, int> (2, 30)); 
    gquiz1.insert(pair <int, int> (3, 60)); 
    gquiz1.insert(pair <int, int> (4, 20)); 
    gquiz1.insert(pair <int, int> (5, 50)); 
    gquiz1.insert(pair <int, int> (6, 50)); 
    gquiz1.insert(pair <int, int> (6, 10)); 
    */
  
    // printing multimap gquiz1 
    multimap <int, char> :: iterator itr; 
    cout << "\nThe multimap gquiz1 is : \n"; 
    cout << "\tKEY\tELEMENT\n"; 
    for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) 
    { 
        cout  <<  '\t' << itr->first 
              <<  '\t' << itr->second << '\n'; 
    } 
    cout << endl; 
  
} 

RELATED TAGS

what
multimap
c++
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring