Last Updated : 23 Jul, 2025
In C++ Stacks are a type of container adaptor with LIFO(Last In First Out) type of work, where a new element is added at one end (top) and an element is removed from that end only. In this article, we will learn to push the elements onto a Stack in C++.
Example:Input:Insert Elements in a Stack in C++
myStack = {40};
Output:
myStack: {40, 30, 20, 10};
To push an element onto a std::stack in C++, we can use the std::stack::push() function, which inserts or pushes the element at the top of the stack. This is the inbuilt function that is provided by the C++ inside the std::stack class template.
C++ Program to Push an Element into a Stack C++
// C++ Program to push an elements onto a stack
#include <iostream>
#include <stack>
using namespace std;
// Driver Code
int main()
{
// Creating empty Stack
stack<int> stackData;
// Pushing elements to the stack
stackData.push(10);
stackData.push(20);
stackData.push(30);
stackData.push(40);
// Printing the updated stack
cout << "Stack: ";
while (!stackData.empty()) {
cout << stackData.top();
stackData.pop();
if (!stackData.empty()) {
cout << ", ";
}
}
cout << endl;
return 0;
}
Stack: 40, 30, 20, 10
Time Complexity: O(N), where N is the number of elements to be inserted.
Auxiliary Space: O(N)
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