Last Updated : 23 Jul, 2025
In C++, stacks are used to store a collection of similar types of data in a Last-In-First-Out (LIFO) manner. In this article, we will discuss how to pop an element from a stack in C++.
Example:Input: myStack = {10, 34, 12, 90, 1}; Output: myStack = {10, 34, 12, 90};Removing an Element from a Stack in C++
In STL, the std::stack::pop() function is used to remove the top element from the stack. However, it’s important to note that this function does not return the popped element. To access the top element before popping it, we can use the std::stack::top() function.
C++ Program to Pop an Element From a Stack C++
// C++ Program to pop an element from a stack
#include <iostream>
#include <stack>
using namespace std;
int main()
{
// Creating a stack with elements
stack<int> stackData;
// Pushing elements to the stack
stackData.push(10);
stackData.push(20);
stackData.push(30);
stackData.push(40);
// Printing the original stack before popping
cout << "Before Popping - Original Stack: ";
stack<int> oStack = stackData;
while (!oStack.empty()) {
cout << oStack.top() << " ";
oStack.pop();
}
cout << endl;
// Popping an element from the stack
if (!stackData.empty()) {
stackData.pop();
}
// Printing the updated stack after popping
cout << "After Popping - Updated Stack: ";
while (!stackData.empty()) {
cout << stackData.top() << " ";
stackData.pop();
}
cout << endl;
return 0;
}
Before Popping - Original Stack: 40 30 20 10 After Popping - Updated Stack: 30 20 10
Time Complexity: O(1)
Auxiliary Space: O(1)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4