stack top() in C++ STL

In this article, we will be discussing the working, syntax, and examples of stack::top() function in C++ STL.

What is Stack in C++ STL?

Stacks are the data structure that stores the data in LIFO (Last In First Out) where we do insertion and deletion from the top of the last element inserted. Like a stack of plates, if we want to push a new plate into the stack we insert on the top and if we want to remove the plate from the stack, we then also remove it from the top.

What is stack::top()?

stack::top() function is an inbuilt function in C++ STL, which is defined in <stack> header file. top() is used to access the element at the top of the stack container. In a stack, the top element is the element that is inserted at the last or most recently inserted element.



The function accepts no parameter(s) −

Return value

This function returns a reference of the element at the top of the stack container.


std::stack<int> odd;




 Live Demo

#include <iostream>
#include <stack&lgt;
using namespace std;
int main(){
   stack<int> stck_1, stck_2;
   //inserting elements to stack 1
   //swapping elements of stack 1 in stack 2 and vice-versa
   cout<<"The top element in stack using TOP(): "<<;
   cout<<"\nElements in stack are: ";
   while (!stck_1.empty()){
      cout<<<<" ";
   return 0;


If we run the above code it will generate the following output −

The top element in stack using TOP(): 4
Elements in stack are: 4 3 2 1