Open In App

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

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

In C++, the stack is a container that follows the LIFO(Last In First Out) rule where new elements are added from one end (top) and removed from that end only. An unordered_map is an associative container that stores elements formed by a combination of key-value pairs, where the key should be unique. In this article, we will learn how to create a stack of unordered_map in C++.

Example:

Input: 
myMap1 = { {“apple”, 1}, {“banana”, 2} }
myMap2 = { {“orange”, 3}, {“mango”, 4} }

Output:
Stack of Unordered_Map: [ { {“orange”, 3}, {“mango”, 4} },
{ {“apple”, 1}, {“banana”, 2} } ]

Stack of Unordered_Map in C++

To create a stack of unordered_map in C++, we need to pass std::unordered_map as the template parameter in the declaration of the stack and then use the std::stack::push() function to insert the unordered_maps in the stack.

Syntax to Declare Stack of Unordered_Maps in C++

stack<unordered_map<key_type, value_type>> stack_name;

Here,

  • key_type is the type of key stored in the unordered_map.
  • value_type is the type of value stored in the unordered_map.
  • stack_name is the name of the stack of unordered_map.

C++ Program to Create Stack of Unordered_Map

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

C++
// C++ Program to illustrate how to create a stack of
// Unordered_Map
#include <iostream>
#include <stack>
#include <unordered_map>

using namespace std;

int main()
{
    // Defining multiple unordered_maps
    unordered_map<int, string> map1
        = { { 1, "One" }, { 2, "Two" }, { 3, "Three" } };
    unordered_map<int, string> map2
        = { { 4, "Four" }, { 5, "Five" }, { 6, "Six" } };

    // Creating a stack of unordered_maps
    stack<unordered_map<int, string> > stackOfMaps;

    // Pushing unordered_maps in the stack
    stackOfMaps.push(map1);
    stackOfMaps.push(map2);

    // Printing elements from the stack of unordered_maps
    cout << "Elements in the Stack of Unordered_Map:"
         << endl;
    while (!stackOfMaps.empty()) {
        unordered_map<int, string> currMap
            = stackOfMaps.top();
        stackOfMaps.pop();

        for (auto& it : currMap) {
            cout << "{" << it.first << ", " << it.second
                 << "} ";
        }
        cout << endl;
    }

    return 0;
}

Output
Elements in the Stack of Unordered_Map:
{6, Six} {4, Four} {5, Five} 
{3, Three} {1, One} {2, Two} 

Time Complexity: O(N), here N is the total number of unordered_maps.
Auxiliary Space: O(N * M), here M is the average number of elements in the unordered_map.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads