Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is C++ Multimap?
2.1.
Syntax of C++ Multimap
2.2.
Properties of Multimap in C++
3.
How to Create a Multimap in C++?
4.
Member Functions in C++ Multimap
5.
Example of Multimap in C++
5.1.
C++
6.
Methods of Initializing a Multimap in C++
7.
Iterator in Multimaps
7.1.
C++
8.
Frequently Asked Questions
8.1.
Why is multimap used?
8.2.
Does multimap sort in C++?
8.3.
What is the difference between multimap and map of sets in C++?
8.4.
How to reverse a multimap in C++?
9.
Conclusion
Last Updated: Jul 3, 2024

Multimap in C++

Author Tanay Kumar
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

The C++ STL (Standard Template Library) supports several Data Structure that play a crucial role in solving any problem. One such data container is the "Multimap in C++". A multimap in C++ is an associative container that stores elements in a mapped fashion. Every element has one key value and one mapped value. Multiple elements can have the same key in a multimap.

Multimap in C++

This article will help you understand the multimap in c++ and the essential functions associated with it.

What is C++ Multimap?

Multimap in c++ is very similar to a map with an addition that multiple items can have the same key value. Also, the key-value pair needs not be unique.

Internally, the elements of a multimap are always sorted by their key values following a specific ordering criterion indicated by its internal comparison object (of type Compare). Keys are always sorted in ascending order.

Syntax of C++ Multimap

#include <map>

std::multimap<key_type, value_type> multimap_name;

Properties of Multimap in C++

  • Multiple Keys: Allows storing multiple pairs with the same key.
  • Sorted Order: Automatically sorts elements by key in ascending order.
  • Key-Value Pairs: Stores elements as key-value pairs, similar to a regular map.
  • Duplicate Keys: Supports duplicate keys, unlike the std::map which requires unique keys.
  • Balanced Tree: Typically implemented as a balanced tree (e.g., red-black tree) for efficient insertion, deletion, and search operations.
  • Iterator Validity: Provides bidirectional iterators for traversing elements in sorted order.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How to Create a Multimap in C++?

We can easily create a multimap with the following syntax:

multimap<key_type , value_type> map_name;

 

The above code will create a multimap with a key of the "Key_type" data type and the "value_type" datatype value. Remember that the key of a multimap and corresponding values are always inserted as a pair. We cannot insert only a key or value in the map.

Now, let’s see an example of creating and initializing multimaps:

#include <bits/stdc++.h>
using namespace std;


int main ()
{
    // Creates a multimap m with keys 3 having two different value 
    multimap<int,int> map_multi{ {1,4} , {2,5} , {3,6}, {3, 7} };
    
    // Creates a multimap with keys of character type and values of integer type
    multimap<string,int> map1;


    
    map1["abc"]=101;    // inserts key = "abc" with value = 101
    map1["b"]=201;      // inserts key = "b" with value = 201
    map1["c"]=301;      // inserts key = "c" with value = 301
    map1["abc"]=401;    // inserts key = "abc" with value = 401
   
    // Create map map3 which is a copy of map m
    multimap<char,int> map3 (map_multi.begin(), map_multi.end());
    
}

 

In the above example, we have created and initialized different multimaps with different methods.

Member Functions in C++ Multimap

For a multimap, many functions or methods are defined, among which the most used ones are the begin, end, empty and size for capacity, find for searching a key, erase and insert for modification.

Now let's learn about them in brief with the below table:

Function

Description

insert()We use it to insert a new element in the multimap.
begin()It returns the iterator to the first element in the multimap container.
end()It returns an iterator to the end of the multimap.
clear()It removes all the elements from the multimap and empties it.
erase()It removes either a single element or a range of elements from the start(inclusive) to end(exclusive).
size()It returns the total number of elements in a multimap container.
empty()It checks if the multimap is empty or not.
swap()It swaps the contents of one multimap with any other multimap of the same key-value type and size.
count(g)It returns the number of matching elements with key =  'g' in the multimap.
find(g)It returns an iterator to the element with the key = 'g' in the multimap if found; otherwise, it returns the iterator to the end.
maxsize()It returns the maximum number of elements the multimap container can hold.

Example of Multimap in C++

Let's consider an example of declaration, insert, find and iteration in a multimap.

  • C++

C++

#include <bits/stdc++.h>
using namespace std;


int main ()
{
          // Creates a  multimap m with keys 3 having two different value
   multimap<int,int> m{ {1,4} , {2,5} , {3,6}, {3, 7} };


   // Using insert() method
   m.insert(pair<int,int> (4,7));  // Inserts new entry of key = 4 and value = 7
   m.insert(make_pair(4, 8));  // Inserts new entry of key = 5 and value = 8


   // Iterating over the multimap
   multimap<int, int>::iterator i;
   for(i = m.begin(); i != m.end(); i++){
       cout << i->first << '\t' << i->second<< '\n';
   }
}

The output for the above code is displayed below:

Output


You can also practice with the help of Online C++ Compiler

Methods of Initializing a Multimap in C++

Initializing a std::multimap in C++ can be done using several methods:

1. Direct Initialization: This initializes myMultimap with key-value pairs using an initializer list.

std::multimap<int, std::string> myMultimap = { {1, "one"}, {2, "two"}, {2, "second"} };

2. Using insert Function: Elements are added using the insert function with std::make_pair.

std::multimap<int, std::string> myMultimap;
myMultimap.insert(std::make_pair(1, "one"));
myMultimap.insert(std::make_pair(2, "two"));
myMultimap.insert(std::make_pair(2, "second"));

3. Range Initialization: Initializes myMultimap using a range of iterators from pairs.begin() to pairs.end().

std::vector<std::pair<int, std::string>> pairs = { {1, "one"}, {2, "two"}, {2, "second"} };
std::multimap<int, std::string> myMultimap(pairs.begin(), pairs.end());

 

Iterator in Multimaps

An iterator to a multimap is an object (like a pointer) pointing to an element inside the multimap container. We can use these iterators to move through the elements of the container.

Syntax:

// Initializing an iterator
multimap<key_type , value_type>::iterator itr;

 

Example:

Let’s consider an example for iterating over the complete map in C++.

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    // Creates a map m with keys 1,2,3 and corresponding values 4,5,6
   multimap<int,int> m{ {1,4} , {2,5} , {3,6} , {3, 7}};


   // Iterating over the map
   multimap<int, int>::iterator i;
   for(i = m.begin(); i != m.end(); i++){
       cout << i->first << '\t' << i->second<< '\n';
   }
}

The output of the above code after iterating through the whole set is displayed below:

Output

Frequently Asked Questions

Why is multimap used?

Multimap in C++ is used when multiple values need to be associated with the same key, allowing storage and retrieval of duplicate keys in a sorted order efficiently.

Does multimap sort in C++?

Yes, std::multimap automatically sorts its elements by key in ascending order. It uses a red-black tree internally to maintain this sorted order.

What is the difference between multimap and map of sets in C++?

A std::multimap allows multiple elements with the same key and sorts elements by key. In contrast, a map of sets (std::map<Key, std::set<Value>>) stores unique keys and allows multiple values per key without sorting by value automatically.

How to reverse a multimap in C++?

You cannot directly reverse a std::multimap because it maintains elements in sorted order by key. To reverse the order of elements, you would typically need to copy the elements to another container and then reverse that container.

Conclusion

In this article, we have extensively discussed the multimap in C++. Understanding std::multimap in C++ provides developers with powerful capabilities for managing collections of key-value pairs where keys can have multiple associated values. With its automatic sorting by key and support for duplicate keys, std::multimap proves invaluable in scenarios requiring efficient storage and retrieval of structured data.

Previous article
Map in C++
Next article
Pairs in Multiset & Multimap in cpp
Live masterclass