VOOZH about

URL: https://www.geeksforgeeks.org/cpp/stack-of-unordered_map-in-cpp/

⇱ How to Create a Stack of Unordered_Map in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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.


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.

Comment