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++ Program to illustrate how to Create a Multimap of // Arrays #include <array> #include <iostream> #include <map> using namespace std;
int main()
{ // Declaration of the multimap with array type as values
multimap< int , array< int , 5> > map;
// Declaration of the arrays
array< int , 5> arr1 = { 10, 20, 30, 40, 50 };
array< int , 5> arr2 = { 1, 3, 5, 7, 9 };
// Inserting keys and their respective arrays into the
// multimap
map.insert({ 1, arr1 });
map.insert({ 2, arr2 });
// Printing the keys and their respective arrays
for ( const auto & pair : map) {
cout << "Key: " << pair.first << ", Values: " ;
for ( int item : pair.second) {
cout << item << " " ;
}
cout << endl;
}
return 0;
} |
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.