Standard Template Library: Using the Stack pop
Method
What is it?
C++ STL Stack pop()
method is used to remove the top element from the stack container. It reduces the size of the stack by one and returns the value of the removed element.
Syntax
The syntax of using the pop() method is:
stack_name.pop();
Where,
stack_name
: It is the name of the stack container.
How to use it
To use the pop()
method, follow the below steps:
- Create a
stack
container and push some values into it. - Call the
pop()
method on thestack
container to remove the top element. - Get the value of the removed element if required.
Program code snippet example
#include <iostream>
#include <stack>
using namespace std;
int main() {
// Creating a stack container and pushing some values into it.
stack<int> myStack;
myStack.push(10);
myStack.push(20);
myStack.push(30);
cout << "Stack size before pop: " << myStack.size() << endl;
// Removing the top element from the stack using pop() method.
myStack.pop();
cout << "Stack size after pop: " << myStack.size() << endl;
// Getting the value of the removed element.
int removed_element = myStack.top();
cout << "Removed element: " << removed_element << endl;
return 0;
}
Output:
Stack size before pop: 3
Stack size after pop: 2
Removed element: 20
Output the stack by accessing the top element.