How to Create a Stack of Multisets in C++?
Last Updated :
06 Mar, 2024
In C++, a stack is a container adapter that operates in a LIFO (Last In First Out) element order and allows insertion and deletion from the end only. A multiset is a container that stores elements in an ordered manner and allows multiple instances of an element. In this article, we will learn how to create a stack of multisets in C++.
Example:
Input:
myMultiset1 = {1, 2, 2, 2};
myMultiset1 = {1, 1, 4, 5};
Output:
myStack: [ {1, 2, 2, 2};
{1, 1, 4, 5}; ]
Stack of Multisets in C++
To create a stack of multisets in C++, we will pass the template parameter in the stack declaration as a multiset. This will create a stack where each element is a multiset in itself.
Syntax to Declare Stack of Multiset
stack <multiset <Type>> myStack;
C++ Program to Create a Stack of Multisets
C++
#include <iostream>
#include <set>
#include <stack>
using namespace std;
int main()
{
multiset< int > myMultiset1 = { 1, 2, 2 };
multiset< int > myMultiset2 = { 1, 1, 2, 2 };
stack<multiset< int > > myStack;
myStack.push(myMultiset1);
myStack.push(myMultiset2);
while (!myStack.empty()) {
multiset< int > topMultiset = myStack.top();
myStack.pop();
cout << "{" ;
for ( auto & elem : topMultiset) {
cout << elem << ", " ;
}
cout << "}, " ;
}
cout << endl;
return 0;
}
|
Output
{1, 1, 2, 2, }, {1, 2, 2, },
Time Complexity: O(N), where N is the number of multisets.
Auxiliary Space: O(N * M), where M is the average size of the multisets.
Share your thoughts in the comments
Please Login to comment...