How to Create a Stack of Multimap in C++?
Last Updated :
06 Mar, 2024
In C++, Stacks are a type of container adaptor with LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. A multimap is a container that stores key-value pairs in an ordered manner. In this article, we will learn how to create a stack of multimaps in C++.
Example:
Input:
myMultimap1 = { {1, “C++”}, {2, “Java”}, {1, “Python”} };
myMultimap2 = { {2, “JavaScript”} };
Output:
myStack: [ { {1, “C++”}, {2, “Java”}, {1, “Python”} },
{ {2, “JavaScript”} } ]
Stack of Multimaps in C++
To create a stack of multimaps in C++, we have to define the type of stack elements as a multimap in the template definition. The stack can store any type of data, including complex data types like multimaps.
Syntax to Declare Stack of Multimap
stack < multimap <keyType, valueType> myStack;
C++ Program to Create a Stack of Multimaps
C++
#include <iostream>
#include <map>
#include <stack>
using namespace std;
int main()
{
multimap< int , string> myMultimap1
= { { 1, "C++" }, { 2, "Java" } };
multimap< int , string> myMultimap2
= { { 1, "Python" }, { 2, "JavaScript" } };
stack<multimap< int , string> > myStack;
myStack.push(myMultimap1);
myStack.push(myMultimap2);
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:
[ { {1, Python}, {2, JavaScript}, } { {1, C++}, {2, Java}, } ]
Time Complexity: O(N) where n is the number of multimaps.
Auxiliary Space: O(N * M), where M is the average size of the multimaps.
Share your thoughts in the comments
Please Login to comment...