
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Implement Stack in STL
Stack is a linear data structure that follows the Last In First Out (LIFO) principle. In this article, we will learn how to use the stack container from the Standard Template Library (STL) in C++.
What is Stack?
A stack is a container that stores data in a way that the last inserted data will be the first to be removed. This is same as a stack of plates, where the last plate placed on the top is the first one to be removed. The STL library of C++ provides a pre-defined stack data structure which comes with all the operations available for a stack.
For example, the below section shows how data are inserted and removed from a stack:
// Declare a stack stack<int> s; // Add Data s.push(10); s.push(20); s.pop(); // This operation will remove 20 from stack
Using stack Container in STL
The stack container is defined in the <stack> header of STL. It provides a LIFO data structure with basic operations such as push, pop, top, and size. Below are some points about this container:
- Header: <stack>
-
Syntax:
stack<datatype> stack_name;
- Common functions:
- push() - Function used to insert an element at the top of the stack.
- pop() - Function used to remove an element from the top of the stack.
- top() - Function used to access the top element of the stack.
- empty() - Function used to check if the stack is empty.
- size() - Function used to return the size of the stack.
Steps to Implement Stack in C++ STL
Following are steps/algorithm to use stack using C++ STL:
- Include the <stack> header file.
- Declare a stack with desired data type.
- Use push() to insert elements.
- Use pop() to remove elements from top.
- Access elements using top().
- Use empty() and size() to check status.
C++ Program to Implement Stack using STL
The below code is the implementation of the above algorithm in C++ language.
#include <iostream> #include <stack> using namespace std; int main() { stack<int> s; // Insert elements s.push(10); s.push(20); s.push(30); cout << "Top Element: " << s.top() << endl; // Remove one element s.pop(); cout << "After one pop operation:" << endl; cout << "Top Element: " << s.top() << endl; cout << "Stack Size: " << s.size() << endl; // Check if empty if (s.empty()) { cout << "Stack is empty" << endl; } else { cout << "Stack is not empty" << endl; } return 0; }
The output of above code will be
Top Element: 30 After one pop operation: Top Element: 20 Stack Size: 2 Stack is not empty
Time and Space Complexity
- push(), pop(), top(): O(1) for each operation.
Space Complexity: O(n), where n is the number of elements in the stack.