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

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.