In C++, the Standard Template Library (STL) provides a versatile container called std::stack
for implementing a stack data structure. A stack is a Last-In-First-Out (LIFO) data structure, meaning that the element inserted last will be the first one to be removed. The std::stack
container encapsulates this behavior and provides a simple interface for stack operations.
Declaration
#include <stack>
std::stack<int> myStack; // Declaring a stack of integers
Functions of Stack
1 push()
Inserts an element onto the top of the stack.
#include <iostream>
#include <stack>
int main() {
std::stack<int> myStack;
myStack.push(5); // Pushing element 5 onto the stack
return 0;
}
Time Complexity: O(1)
2 pop()
Removes the top element from the stack. It does not return any thing.
#include <iostream>
#include <stack>
int main() {
std::stack<int> myStack;
myStack.push(5);
myStack.pop(); // Removing the top element from the stack
return 0;
}
Time Complexity: O(1)
3 top()
Accesses the top element of the stack without removing it.
#include <iostream>
#include <stack>
int main() {
std::stack<int> myStack;
myStack.push(5);
int topElement = myStack.top(); // Accessing the top element of the stack
std::cout << "Top element: " << topElement << std::endl;
return 0;
}
// Output
Top element: 5
Time Complexity: O(1)
4 size()
Returns the number of elements in the stack
#include <iostream>
#include <stack>
int main() {
std::stack<int> myStack;
myStack.push(5);
int stackSize = myStack.size(); // Getting the size of the stack
std::cout << "Stack size: " << stackSize << std::endl;
return 0;
}
// Output
Stack size: 1
Time Complexity: O(1)
5 empty()
Checks if the stack is empty
#include <iostream>
#include <stack>
int main() {
std::stack<int> myStack;
bool isEmpty = myStack.empty(); // Checking if the stack is empty
if (isEmpty) {
std::cout << "Stack is empty" << std::endl;
}
return 0;
}
// Output
Stack is empty
Time Complexity: O(1)