C++ Standard Library C++ STL Library

C++ <stack> - top() Function



The C++ stack::top function returns a reference to the top element of the stack. In a stack, addition and deletion of a element occurs from the top of the stack. Hence, The most recently added element will be the top element of the stack.

Syntax

value_type& top();
const value_type& top() const;
reference& top();
const_reference& top() const;

Parameters

No parameter is required.

Return Value

A reference to the top element of the stack.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the stack::top function is used to access the top element of the stack MyStack.

#include <iostream>
#include <stack>
using namespace std;
 
int main (){
  stack<int> MyStack;

  MyStack.push(10);
  MyStack.push(20);
  MyStack.push(30);
  MyStack.push(40);
  MyStack.push(50);

  cout<<"The top element of MyStack is: ";
  cout<<MyStack.top()<<endl;

  cout<<"Delete the top element of MyStack.\n";
  MyStack.pop();

  cout<<"Now, The top element of MyStack is: ";
  cout<<MyStack.top();  
  return 0;
}

The output of the above code will be:

The top element of MyStack is: 50
Delete the top element of MyStack.
Now, The top element of MyStack is: 40

❮ C++ <stack> Library