In C++, a stack is a container adapter that provides a last-in, first-out (LIFO) type of data structure with two major operations, namely push and pop while Bitset is a container that can store N bits and provides constant-time operations to manipulate individual bits. In this article, we will learn how to create a stack of bitsets in C++.
Example:
Input: myBitset1 = {1, 0, 1}; myBitset2 = {0, 1, 1}; Output: myStack: [ {1, 0, 1}, {0, 1, 1} ]
Stack of Bitsets in C++
To create a stack of bitsets in C++, we have to pass the bitset as the type of the element in the stack declaration. The bitset will be passed as the template argument while creating the instance of a std::stack class template.
Syntax to Declare Stack of Bitset
stack <bitset <size>> myStack
C++ Program to Create Stack of Bitset
// C++ Program to illustrate how to create a stack of // bitsets #include <bitset> #include <iostream> #include <stack> using namespace std;
int main()
{ // Initialize two bitsets
bitset<3> myBitset1( "101" );
bitset<3> myBitset2( "011" );
// Create a stack of bitsets
stack<bitset<3> > myStack;
myStack.push(myBitset1);
myStack.push(myBitset2);
// Print the stack of bitsets
while (!myStack.empty()) {
bitset<3> topBitset = myStack.top();
myStack.pop();
cout << topBitset << ", " ;
}
cout << endl;
return 0;
} |
011, 101,
Time Complexity: O(N) where N is the number of bitsets.
Auxiliary Space: O(N * M), where M is the size of each bitset.