How To Insert Multiple Key-Value Pairs Into a Multimap in C++?
Last Updated :
01 Mar, 2024
Improve
In C++, a multimap is similar to a map that stores the data in the key-value format and it also allows us to store duplicate keys for the same value. In this article, we will learn how to insert multiple Key-Value pairs efficiently into a multimap.
Example:
Input: multi_map = {{"Manas","Singing" }, {"Manas","Dancing" }} Output: Multimap after Insertion: Manas-> Singing Manas-> Dancing Salma-> Reading Salma-> Painting Salma-> Arts Soumya-> Music
Add Multiple Key-Value Pairs in a Multimap in C++
We can use the std::multimap::insert in C++ STL to insert elements in the std::multimap container by passing all the key-value pairs inside the insert() function at once.
C++ Program to Add Multiple Key-Value Pairs in a Multimap
The below program demonstrates how we can insert multiple key-value pairs at a time in a multimap in C++ STL.
// C++ Program insert Multiple Items Into a Multimap
#include <iostream>
#include <map>
using namespace std;
int main()
{
multimap<string, string> hobbies
= { { "Manas", "Singing" },
{ "Manas", "Dancing" } };
// inserting multiple key-value pairs in a map
hobbies.insert({ { "Salma", "Reading" },
{ "Soumya", "Music" },
{ "Salma", "Painting" },
{ "Salma", "Arts" } });
// Displaying the elements pf multimap
cout << "Multimap after Insertion: " << endl;
for (const auto& key_value : hobbies) {
string key = key_value.first;
string value = key_value.second;
cout << key << "-> " << value << endl;
}
return 0;
}
28
1
// C++ Program insert Multiple Items Into a Multimap
2
3
4
5
using namespace std;
6
7
int main()
8
{
9
multimap<string, string> hobbies
10
= { { "Manas", "Singing" },
11
{ "Manas", "Dancing" } };
12
13
// inserting multiple key-value pairs in a map
14
15
hobbies.insert({ { "Salma", "Reading" },
16
{ "Soumya", "Music" },
17
{ "Salma", "Painting" },
18
{ "Salma", "Arts" } });
19
20
// Displaying the elements pf multimap
21
cout << "Multimap after Insertion: " << endl;
22
for (const auto& key_value : hobbies) {
23
string key = key_value.first;
24
string value = key_value.second;
25
cout << key << "-> " << value << endl;
26
}
27
return 0;
28
}
Output
Multimap after Insertion: Manas-> Singing Manas-> Dancing Salma-> Reading Salma-> Painting Salma-> Arts Soumya-> Music
Time Complexity: O(M * log(N)), where N is the number of elements in the multimap and M is the number of elements to be inserted.
Auxilliary Space: O(M)