Creating a Stack of Unordered Sets in C++
To create a std::stack of std::unordered_set, we can use the std::stack template class that takes the type of the elements as a template parameter. We can define this type as of unordered_set of a given type.
Syntax to Declare Stack of Unordered Set
stack<unordered_set<Type>> myStack
C++ Program to Create Stack of Unordered Set
C++
// C++ program to illustrate how to create a stack of // unordered sets in C++ #include <iostream> #include <stack> #include <unordered_set> using namespace std; int main() { // Declaring a stack of unordered sets stack<unordered_set< int > > myStack; // Creating some unordered sets unordered_set< int > set1 = { 1, 2, 3 }; unordered_set< int > set2 = { 4, 5, 6 }; unordered_set< int > set3 = { 7, 8, 9 }; // Pushing unordered sets into the stack myStack.push(set1); myStack.push(set2); myStack.push(set3); // Checking if the stack is empty cout << "Stack Elements: " << endl; while (!myStack.empty()) { auto ele = myStack.top(); int count = 1; cout << "uSet" << count << ": " ; for ( auto i : ele) { cout << i << " " ; } count++; cout << endl; myStack.pop(); } return 0; } |
Stack Elements: uSet1: 9 7 8 uSet1: 6 4 5 uSet1: 3 1 2
Time Complexity: O(N) where, N is the number of unordered sets.
Auxiliary Space: O(N)
How to Create Stack of Unordered Set in C++?
In C++, a stack is a container adapter that provides a Last-In-First-Out (LIFO) type of data structure, and an unordered set is a container that stores unique elements in no particular order. In this article, we will learn how to create a stack of unordered sets in C++.