stack top() in C++ STL

C++Server Side ProgrammingProgramming

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.

Syntax

stack_name.top();

Parameters

The function accepts no parameter(s) −

Return value

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

Input 

std::stack<int> odd;
odd.emplace(1);
odd.emplace(3);
odd.emplace(5);
odd.top();

Output

5

Example

 Live Demo

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

Output

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
raja
Published on 22-Apr-2020 12:24:26

Advertisements