- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
'; 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
#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
- Related Questions & Answers
- stack empty() and stack size() in C++ STL
- stack emplace() in C++ STL
- stack swap() in C++ STL
- Stack in C++ STL(3.5)
- C++ Program to Implement Stack in STL
- stack push() and pop() in C++ STL
- How to get top activity name in activity stack?
- Get object at the top of the Stack in C#
- Insert an object at the top of the Stack in C#
- How to bring an activity to foreground i.e. top of stack in Android?
- How to bring an activity to the foreground i.e. top of stack using Kotlin?
- Stack and the stack pointer in 8085 Microprocessor
- Stack in Java
- Stack Class in C#
- Stack in Java Programming
Previous Page Print PageNext Page
Advertisem*nts
';adpushup.triggerAd(ad_id);});