Home »
C++ STL
stack::pop() function in C++ STL
C++ STL stack::pop() function with example: In this article, we are going to see how to pop an element from a stack using C++ STL?
Submitted by Radib Kar, on February 03, 2019
Prototype
stack<T> st; //declaration
st.pop();
Parameter
No parameter passed
Return type
void
Header file to be included:
#include <iostream>
#include <stack>
OR
#include <bits/stdc++.h>
Usage:
The function pops the top element from the stack.
Time complexity: O(1)
Example:
For a stack of integer,
stack<int> st;
st.push(4);
st.push(5);
stack content:
5 <-- TOP
4
st.pop(); //one pop operation performed
stack content:
4 <-- TOP
st.pop(); //one pop operation performed
stack content:
empty stack
C++ implementation:
#include <bits/stdc++.h>
using namespace std;
int main(){
cout<<"...use of pop function...\n";
int count=0;
stack<int> st; //declare the stack
st.push(4); //pushed 4
st.push(5); //pushed 5
st.push(6);
cout<<"stack elements are:\n";
while(!st.empty()){//stack not empty
cout<<"top element is:"<<st.top()<<endl;//print top element
st.pop();
count++;
}
cout<<"stack empty\n";
cout<<count<<" pop operation performed total to make stack empty\n";
return 0;
}
Output:
...use of pop function...
stack elements are:
top element is:6
top element is:5
top element is:4
stack empty
3 pop operation performed total to make stack empty