How to Create a Multimap of Arrays in C++?
Last Updated :
28 Feb, 2024
In C++, a multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. In this article, we will learn how to create a multimap of arrays in C++ STL.
Example
Input:
myArray1 = [“John”, “Doe”];
myArray2 = [“Adam”, “Smith”];
Output:
Multimap: {1 -> [“John”, “Doe”], 2 -> [“Adam”, “Smith”]}
Multimap of Arrays in C++ STL
In C++ STL, you can create a multimap
of arrays by specifying the array type as the value type of the multimap
. We can choose the key of our desired type. After that, we can insert the element into the multimap using the std::multimap::insert() function.
Syntax
multimap<int, array<int, 5> > myMultimap;
C++ Program to Create a Multimap of Arrays
C++
#include <array>
#include <iostream>
#include <map>
using namespace std;
int main()
{
multimap< int , array< int , 5> > map;
array< int , 5> arr1 = { 10, 20, 30, 40, 50 };
array< int , 5> arr2 = { 1, 3, 5, 7, 9 };
map.insert({ 1, arr1 });
map.insert({ 2, arr2 });
for ( const auto & pair : map) {
cout << "Key: " << pair.first << ", Values: " ;
for ( int item : pair.second) {
cout << item << " " ;
}
cout << endl;
}
return 0;
}
|
Output
Key: 1, Values: 10 20 30 40 50
Key: 2, Values: 1 3 5 7 9
Time Complexity: O(N * logN), where N is the number of arrays.
Space Complexity: O(N * M), where M is the average size of the arrays.
Share your thoughts in the comments
Please Login to comment...