In C++, maps are associative containers provided by the STL library of C++, that allow the users to store data in key-value pairs where the keys must be unique. In this article, we will learn how to create a map of maps in C++.
For Example,
Input: myMap1={1, "C++"}; myMap2={1, "Java"}; myMap3={2, "Python"}; Output: Map Elements: { {1: {1, "C++"} }, {2: {1, "Java"} }, {3: {2, "Python"} }
Map of Maps in C++
To create a std::map of maps first, we need to declare a map where the key is of the desired type and the value is of the type map. We can do that by passing the value template parameter as a map.
Syntax to Declare Map of Maps
map < keytype, map <innerKeyType, valueType> > myMapC++ Program to Create a Map of Maps
The below program demonstrates how we can create a map of maps in C++ STL.
// C++ program to illustrate how to create a map of maps
#include <iostream>
#include <map>
using namespace std;
int main()
{
// Creating a map of maps
map<int, map<int, string> > myMap;
// Adding key-value pairs to the map of maps
myMap[1][1] = "one";
myMap[1][2] = "two";
myMap[2][1] = "two";
myMap[2][2] = "four";
// Printing the map of maps
cout << "Map of maps:" << endl;
for (const auto& pair1 : myMap) {
for (const auto& pair2 : pair1.second) {
cout << pair1.first << ", " << pair2.first
<< " => " << pair2.second << endl;
}
}
return 0;
}
Output
Map of maps: 1, 1 => one 1, 2 => two 2, 1 => two 2, 2 => four
Time Complexity: O(N * M log(N*M) ), here N is the number of maps in the map and M is the average size of the inner maps
Auxiliary Space: O(N * M)