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

Prototype

    stack st; //declaration
    st.push(T item);

Parameter

    T item; //T is the data type

Return type

void

Header file to be included

    #include <iostream>
    #include <stack>
    OR
    #include <bits/stdc++.h>

Usage

The function pushes elements to the stack.

Time complexity: O(1)

Example:

    For a stack of integer,
    stack<int> st;
    st.push(4);
    st.push(5);

    stack content:
    5 <- TOP
    4

stack::push() function Exaxmple

#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.