Stack is a Linear Data Structure that is based on LIFO (Last In First Out) principle and we also have a Stack container class in C++ STL (Standard Template Library) that is implemented based on the same LIFO principle.
When you use STL Stack, you don't have to worry about the implementation part of the stack operations like push(), pop(), top(), and empty() because in STL Stack all these operations are already provided in the form of a member function. You can directly use these member functions inside your program without thinking about the implementation part.
Important Stack STL member functions:
- push(): It is used to insert an element at the top end of the Stack.
- pop(): It is used to delete the topmost element of the Stack.
- top(): It returns the topmost element present in the Stack. This function just returns the value present on the top it does not remove that element from the Stack.
- empty(): It is a boolean function that will return true if Stack is empty else it will return false.
- size(): It is used to get the count of the number of elements present in the Stack.
Syntax: stack<datatype> stackname;
Example: C++ code for STL Stack.
#include <iostream> #include <stack> using namespace std; int main() { stack<int> st; st.push(50); st.push(40); st.push(30); st.push(20); st.push(10); cout << "Element present at the top: " << st.top() << endl; // delete top element of the stack st.pop(); cout << "Top element after deletion: " << st.top() << endl; if (st.empty()) { cout << "Stack is Empty." << endl; } else { cout << "Stack is not Empty." << endl; } cout << "Number of element present in stack " << st.size() << endl; }
Element present at the top: 10
Top element after deletion: 20
Stack is not Empty.
Number of element present in stack 4
No comments:
Post a Comment