Open In App

How to Store Maps in a Map in C++?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a map is a container that stores elements as a key value and a mapped value. A set is a container that stores unique elements in a particular order. In this article, we will learn how to create a map of sets in C++ STL.

Example:

myMap: { {1, {{1, "Apple"}, {2, "Banana"}}},
                 {2, {{3, "Cherry"}, {4, "Date"}}} }

Store std::maps in Another std::map in C++

To store maps in a map in C++, we can simply define the value type of the outer map as another map. This allows us to store key-value pairs where the values themselves are maps.

Syntax

map <outerKeyType, map<innerKeyType, innerValueType>> mapName

C++ Program to Store Maps in a Map

C++




// C++ program that demonstrates how to store maps in a map
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
    // Initialize a map of maps
    map<int, map<int, string> > myMap
        = { { 1, { { 1, "Apple" }, { 2, "Banana" } } },
            { 2, { { 3, "Cherry" }, { 4, "Date" } } } };
  
    // Print the map of maps
    for (const auto& pair1 : myMap) {
        cout << pair1.first << ":\n";
        for (const auto& pair2 : pair1.second) {
            cout << "  " << pair2.first << ": "
                 << pair2.second << "\n";
        }
    }
  
    return 0;
}


Output

1:
  1: Apple
  2: Banana
2:
  3: Cherry
  4: Date

Time Complexity: O(N log N), where N is the number of inner maps.
Space Complexity: O(N * M), M is the average size of the inner maps.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads