
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
Stack in C++ STL
In C++ STL, stack is used as container which is implemented as LIFO structure. LIFO means Last In First Out. Stack can view as a pile of books in which the books are arranged one above the another and the last inserted book will be the first one to be removed that’s why it is called as a LIFO structure.
The operations associated with the stack are -
-
Top() - This function returns the reference to the topmost element of a stack.
Syntax - name_of_stack.top()
Parameters - No Parameter
Return Value - Reference to the topmost element of a stack container
-
Push() - This function is used to insert the element to the stack container.
Syntax - name_of_stack.push(element)
Parameters - this function takes the element to be inserted.
Return Value - It doesn’t return anything.
-
Pop() - This function is used to remove the element from the stack container.
Syntax - name_of_stack.pop()
Parameters - No Parameter
Return Value - It removes the topmost element of a stack and returns it.
-
Size() - This function is used to calculate the total number of elements present in a stack.
Syntax - name_of_stack.size()
Parameters - No Parameter
Return Value - It returns the number of elements in a stack.
-
Empty() - This function is used to check whether the stack is empty or not
Syntax - name_of_stack.empty()
Parameters - No Parameter
Return Value - It returns the Boolean value that is either true or false. True when stack is empty and false when stack is not empty.
Example
#include <bits/stdc++.h> using namespace std; int main(){ //create a stack container stack <int> newStack; //insert elements to a stack newStack.push(10); newStack.push(20); newStack.push(30); newStack.push(40); //check whether the values are pushed in stack or not //using empty() if(!newStack.empty()){ //calculate size of a stack cout<<"Stack size is: "<< newStack.size(); } else{ cout<<"Stack is empty"; } cout<<"\nElements in the stack are:"; while(!newStack.empty()){ cout<<" "<< newStack.top(); newStack.pop(); } return 0; }
Output
Stack size is: 4 Elements in the stack are: 40 30 20 10