×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.