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++ Program to illustrate how to create a stack of // multisets #include <iostream> #include <set> #include <stack> using namespace std;
int main()
{ // Initialize a multiset with some entries
multiset< int > myMultiset1 = { 1, 2, 2 };
multiset< int > myMultiset2 = { 1, 1, 2, 2 };
// Create a stack of multisets
stack<multiset< int > > myStack;
myStack.push(myMultiset1);
myStack.push(myMultiset2);
// Print the stack of multisets
while (!myStack.empty()) {
multiset< int > topMultiset = myStack.top();
myStack.pop();
cout << "{" ;
for ( auto & elem : topMultiset) {
cout << elem << ", " ;
}
cout << "}, " ;
}
cout << endl;
return 0;
} |
{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.