Home » C++ STL

stack::top() function in C++ STL

C++ STL stack::top() function with example: In this article, we are going to see how to return the current top element of a stack using C++ STL?
Submitted by Radib Kar, on February 03, 2019

Prototype:

    stack<T> st; //declaration
    T st.top();

Parameter:

    No parameter passed

Return type: T //data type

Header file to be included:

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

Usage:

The function returns the current top element of a stack. (no change in stack status)

Time complexity: O(1)

Example:

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

    int temp=st.top() //5
    Print temp // prints 5
    stack content: //same as before, it don't change stack status
    5 <-- TOP
    4

C++ implementation:

#include <bits/stdc++.h>
using namespace std;

int main(){
    cout<<"...use of top function...\n";
    int count=0;
    stack<int> st; //declare the stack
    st.push(4); //pushed 4
    st.push(5); //pushed 5
    st.push(6);
    
    cout<<"stack elements are:\n";
    while(!st.empty()){//stack not empty
        cout<<"top element is:"<<st.top()<<endl;//print top element
        st.pop();
        count++;
    }
    cout<<"stack empty\n";
    cout<<count<<" pop operation performed total to make stack empty\n";
    return 0;   
}

Output

...use of top function...
stack elements are:
top element is:6
top element is:5
top element is:4
stack empty
3 pop operation performed total to make stack empty





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







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.