stack top() in C++ STL (2024)

'; var adpushup = adpushup || {}; adpushup.que = adpushup.que || []; adpushup.que.push(function() { adpushup.triggerAd(ad_id); });

In this article, we will be discussing the working, syntax, and examples ofstack::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 itfrom 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<<"
Elements 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(): 4Elements in stack are: 4 3 2 1

stack top() in C++ STL (23)

Updated on 22-Apr-2020 12:25:00

Advertisem*nts

';adpushup.triggerAd(ad_id);});

stack top() in C++ STL (2024)

FAQs

What does STL stack top do? ›

What does STL stack top do?

How to display stack elements in C++ STL? ›

How to display stack elements in C++ STL?

How is stack implemented in C++ STL? ›

How is stack implemented in C++ STL?

How to pop the top of a stack in C++? ›

How to pop the top of a stack in C++?

Top Articles
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 5892

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.