stack::top() in C++ STL

Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only.

stack::top()

top() function is used to reference the top(or the newest) element of the stack.

Syntax :

stackname.front()
Parameters :
No value is needed to pass as the parameter.
Returns :
Direct reference to the top element of the stack container.

Examples:

Input  : stackname.push(5);
         stackname.push(1);
         stackname.top();
Output : 1

Input  : stackname.push(5);
         stackname.push(1);
         stackname.push(2);
         stackname.top();
Output : 2

Errors and Exceptions



1. If the stack container is empty, it causes undefined behaviour
2. It has a no exception throw guarantee if the stack is not empty

// CPP program to illustrate
// Implementation of top() function
#include <iostream>
#include <stack>
using namespace std;

int main()
{
    stack<int> mystack;
    mystack.push(5);
    mystack.push(1);
    mystack.push(2);

    // Stack top
    cout << mystack.top();
    return 0;
}

Output:

2

Application :
Given a stack of integers, find the sum of the all the integers.

Input : 1, 8, 3, 6, 2
Output: 20

Algorithm
1. Check if the stack is empty, if not add the top element to a variable initialised as 0, and pop the top element.
2. Repeat this step until the stack is empty.
3. Print the final value of the variable.

// CPP program to illustrate
// Application of top() function
#include <iostream>
#include <stack>
using namespace std;

int main()
{
    int sum = 0;
    stack<int> mystack;
    mystack.push(1);
    mystack.push(8);
    mystack.push(3);
    mystack.push(6);
    mystack.push(2);

    // Stack becomes 1, 8, 3, 6, 2

    while (!mystack.empty()) {
        sum = sum + mystack.top();
        mystack.pop();
    }
    cout << sum;
    return 0;
}

Output:

20


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Practice Tags :

Recommended Posts:



1 Average Difficulty : 1/5.0
Based on 1 vote(s)






User Actions