How to Create a Stack of Set in C++?
Last Updated :
05 Mar, 2024
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++
#include <iostream>
#include <set>
#include <stack>
using namespace std;
int main()
{
stack<set< int > > myStack;
set< int > set1 = { 1, 2, 3 };
set< int > set2 = { 4, 5, 6 };
set< int > set3 = { 7, 8, 9 };
myStack.push(set1);
myStack.push(set2);
myStack.push(set3);
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)
Share your thoughts in the comments
Please Login to comment...