How to Insert a Pair in Multimap in C++?
Last Updated :
09 Feb, 2024
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++
#include <iostream>
#include <map>
#include <utility>
using namespace std;
int main()
{
multimap< int , string> myMultimap;
auto myPair = make_pair(1, "Another One" );
myMultimap.insert(make_pair(1, "One" ));
myMultimap.insert({ 2, "Two" });
myMultimap.insert(myPair);
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.
Share your thoughts in the comments
Please Login to comment...