Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ stack::top function is used to return 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 below example, 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();

  cout<<"\n\nDelete the newest element of MyStack.\n\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 newest element of MyStack.

Now, The top element of MyStack is: 40

❮ C++ <stack> Library