Open In App

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

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the stack is a container in which new elements are added from one end (top) and removed from that end only. In this article, we will learn how to create a stack of unordered_multiset in C++.

Example:

Input: 
mySet1 = { “apple”, “banana”, “apple” }
mySet2 = { “orange”, “mango”, “orange” }

Output:
Stack of Unordered_Multiset: [ { “orange”, “mango”, “orange” },
{ “apple”, “banana”, “apple” } ]

Stack of Unordered_Multiset in C++

To create a stack of std::unordered_multiset in C++, first declare a std::stack with std::unordered_multiset as the template argument, then use the std::stack::push() function to insert the unordered_multiset in the stack.

Syntax to Create a Stack of Unordered_Multiset in C++

stack<unordered_multiset<datatype>> stack_name;

Here,

  • datatype denotes the type of data stored in the unordered_multiset.
  • stack_name is the name of the stack of unordered_multiset.

C++ Program to Create a Stack of Unordered_Multiset

The below program demonstrates how we can create and use a stack of unordered_multiset in C++ STL.

C++
// C++ Program to illustrate how to create a stack of
// unordered_multiset
#include <iostream>
#include <stack>
#include <unordered_set>

using namespace std;

int main()
{

    // Defining multiple unordered_multisets
    unordered_multiset<string> s1
        = { "apple", "banana", "apple" };
    unordered_multiset<string> s2
        = { "orange", "mango", "orange" };

    // Create a stack of unordered_multisets
    stack<unordered_multiset<string> > stackOfSets;

    // Pushing unordered_multisets into the stack
    stackOfSets.push(s1);
    stackOfSets.push(s2);

    // Printing elements from the stack of
    // unordered_multisets
    cout << "Elements in the Stack of Unordered_Multiset:"
         << endl;
    while (!stackOfSets.empty()) {
        unordered_multiset<string> currSet
            = stackOfSets.top();
        stackOfSets.pop();

        for (auto& it : currSet) {
            cout << it << " ";
        }
        cout << endl;
    }

    return 0;
}

Output
Elements in the Stack of Unordered_Multiset:
orange orange mango 
apple apple banana 

Time Complexity: O(N), here N is the total number of elements in each unordered_multiset.
Auxiliary Space: O(M * N), here M is the number of unordered_multiset.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads