Stack of Unordered_Multimaps in C++
To create a std::stack of std::unordered_multimaps in C++, we have to define the type of stack elements as an unordered_multimap in the template definition.
Syntax to Declare Stack of Unordered_Multimap
stack < unordered_multimap <keyType, valueType> > myStack;
Here,
key_type
is the type of key stored in the unordered_multimapvalue_type
is the type of value stored in the unordered_multimap.myStack
is the name of the stack of unordered_multimap.
C++ Program to Create Stack of Unordered_Multimap
The below program demonstrates how we can create and use a stack of unordered_multimap in C++ STL.
// C++ Program to illustrate how to create a stack of
// unordered_multimaps
#include <iostream>
#include <stack>
#include <unordered_map>
using namespace std;
int main()
{
// Initialize an unordered_multimap with some entries
unordered_multimap<int, string> myUnorderedMultimap1
= { { 1, "C++" }, { 2, "Java" }, { 1, "Python" } };
unordered_multimap<int, string> myUnorderedMultimap2
= { { 2, "JavaScript" }, { 3, "R" } };
;
// Create a stack of unordered_multimaps
stack<unordered_multimap<int, string> > myStack;
myStack.push(myUnorderedMultimap1);
myStack.push(myUnorderedMultimap2);
// Print unordered_multimap in the stack
cout << "myStack:" << endl << "[";
while (!myStack.empty()) {
auto ele = myStack.top();
cout << " { ";
for (auto& pair : ele) {
cout << "{" << pair.first << ", " << pair.second
<< "}, ";
}
cout << " } ";
myStack.pop();
}
cout << " ]";
return 0;
}
Output
myStack: [ { {3, R}, {2, JavaScript}, } { {1, Python}, {1, C++}, {2, Java}, } ]
Time Complexity: O(N), here N is the total number of elements across all unordered_multimaps.
Auxiliary Space: O(N)
How to Create a Stack of Unordered_Multimap in C++?
In C++, an unordered_multimap is an associative container that contains key-value pairs allowing multiple elements with the same key. In this article, we will learn how to create a stack of unordered_multimaps in C++.
Example:
Input: myMultimap1 = { {1, “C++”}, {2, “Java”}, {1, “Python”} }; myMultimap2 = { {2, “JavaScript”}, {3, "R" }}; Output: myStack: [ { {1, “C++”}, {2, “Java”}, {1, “Python”} }, { {2, “JavaScript”} } ]