Home »
C++ STL
stack::push() function in C++ STL
C++ STL stack::push() function with example: In this article, we are going to see how to push an element into a stack using C++ STL?
Submitted by Radib Kar, on February 03, 2019
C++ STL - stack::push() Function
The push() function is used to insert a new element at the top of the stack, above its current top element.
Syntax
stack<T>t; st; //declaration
st.push(T item);
Parameter(s)
- item - Item to be inserted.
Return value
This function does not return any value.
Header file
Header file to be included:
#include <iostream>
#include <stack>
OR
#include <bits/stdc++.h>
Time complexity
The time complexity is O(1).
Sample Input and Output
For a stack of integer,
stack<int> st;
st.push(4);
st.push(5);
stack content:
5 <- TOP
4
Example
#include <bits/stdc++.h>
using namespace std;
int main(){
cout<<"...use of push function...\n";
stack<int> st; //declare the stack
st.push(4); //pushed 4
st.push(5); //pushed 5
cout<<"stack elements are:\n";
cout<<st.top()<<endl; //prints 5
st.pop(); //5 popped
cout<<st.top()<<endl; //prints 4
st.pop(); //4 popped
return 0;
}
Output
...use of push function...
stack elements are:
5
4