How to Create a Stack of Set in C++?
In C++ STL, 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. Sets are a type of associative container in which each element is unique and in some sorted order. In this article, we will learn how to create a stack of sets in C++.
Example
Input:
mySet1 = {1, 4, 8, 9, 11}
mySet2 = {1, 2, 3, 5, 7}
Output:
myStack: [ {1, 4, 8, 9, 11}
{1, 2, 3, 5, 7} ]
Creating a Stack of Sets in C++
To create a std::stack of std::set in C++, we can pass the type of the stack container to be of type std::set as a template parameter while declaration.
Syntax to Declare Stack of Set
stack<set<type>> myStack
C++ Program to Create a Stack of Set
C++
// C++ Program to illustrate how to create a stack of set #include <iostream> #include <set> #include <stack> using namespace std; int main() { // Declaring a stack of sets stack<set< int > > myStack; // Creating some sets set< int > set1 = { 1, 2, 3 }; set< int > set2 = { 4, 5, 6 }; set< int > set3 = { 7, 8, 9 }; // Pushing sets into the stack myStack.push(set1); myStack.push(set2); myStack.push(set3); // Checking if the stack is empty cout << "myStack: " << endl; int i = 1; while (!myStack.empty()) { auto ele = myStack.top(); cout << "Set" << i++ << ": " ; for ( auto i : ele) { cout << i << " " ; } cout << endl; myStack.pop(); } return 0; } |
Output
myStack: Set1: 7 8 9 Set2: 4 5 6 Set3: 1 2 3
Time complexity: O(N), where N is the number of sets.
Auxiliary Space: O(N)
Contact Us