Open In App

How to Create a Stack of Map in C++?

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the std::stack is a container that follows the LIFO (Last In, First Out) rule, whereas std::map is an associative container that stores key-value pairs. In this article, we will learn how to create a stack of a map in C++.

Example:

Input: 
myMap = { {1: ‘a’}, {2: ‘b’}, {3: ‘c’} };
myMap = { {4, ‘d’}, {5, ‘e’} };

Output: 
Stack of map: [ { {1: ‘a’}, {2: ‘b’}, {3: ‘c’} }, 
                { {4, ‘d’}, {5, ‘e’} } ]

Stack of Maps in C++

We can create a stack of maps in C++ by passing the std::map type as the template argument during the declaration of the map.

Syntax to Declare Stack of Maps in C++

stack< map<key_datatype, value_datatype>> stack_name;

Here,

  • key_datatype denotes the type of data you want to use as the key in the map.
  • value_datatype denotes the type of data you want to store as the value in the map.
  • stack_name is the name of the stack of map.

C++ Program to Create Stack of Map

The below program demonstrates how we can create a stack of map in C++ STL.

C++
// C++ Program to illustrate how to create a stack of maps
#include <iostream>
#include <map>
#include <stack>
using namespace std;

int main()
{
    // Define the type of map
    typedef map<int, string> MapType;

    // Initialize two maps
    MapType map1 = { { 1, "C++" }, { 2, "Java" } };
    MapType map2 = { { 3, "Python" }, { 4, "JavaScript" } };

    // Create a stack of maps
    stack<MapType> myStack;
    myStack.push(map1);
    myStack.push(map2);

    // Print the stack of maps
    while (!myStack.empty()) {
        MapType& topMap = myStack.top();
        for (auto& pair : topMap) {
            cout << "{" << pair.first << ", " << pair.second
                 << "}, ";
        }
        cout << endl;
        myStack.pop();
    }

    return 0;
}

Output
{3, Python}, {4, JavaScript}, 
{1, C++}, {2, Java}, 

Time Complexity: O(N), here N is the number of maps.
Auxiliary Space: O(N * M), where M is the size of each map


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads