Open In App

How to Insert a Pair in Multimap in C++?

In C++, we have multimap which is used to store key-value pairs like a map but multimap can have multiple values for the same key. In this article, we will learn how to insert a pair into a multimap in C++.

Example



Input:
myMultimap = { {1, "this"}, {2,"is"}}
myPair = {2, "was"};

Output:
myMultimap = { {1, "this"}, {2,"is"}, {2, "was"}}

Inserting Pairs into Multimap in C++

To insert a pair into a multimap, we can use the std::multimap::insert() function that allows us to add the pair object to the multimap. First, create a multimap, then pass the pair you want to insert in the multimap to the insert() function.

C++ Program to Insert Pair into Multimap

The below demonstrates the use of the insert() function to insert pairs into a multimap.






// C++ program to insert pair into a multimap
  
#include <iostream>
#include <map>
#include <utility>
using namespace std;
  
int main()
{
    // Creating a multimap
    multimap<int, string> myMultimap;
  
    // create a pair
    auto myPair = make_pair(1, "Another One");
  
    // Inserting a pair using the insert
    // member function
    myMultimap.insert(make_pair(1, "One"));
    myMultimap.insert({ 2, "Two" });
    myMultimap.insert(myPair);
  
    // Displaying the multimap
    for (const auto& pair : myMultimap) {
        cout << pair.first << ": " << pair.second << endl;
    }
  
    return 0;
}

Output
1: One
1: Another One
2: Two

Time Complexity: O(log N)
Auxiliary Space: O(1)

We can also use emplace() function to insert pair into a multimap.

Article Tags :