Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

What is stack.top() in C++?

Harris Amjad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The stack.top() function in C++ is used to get the reference of the element at the top of the stack.

The following illustration shows a visual representation of the stack.top() function.

A visual representation of stack.top()

In order to use the stack.top() function, we must include stack in the program, as shown below:

#include <stack>

Syntax

stack_name.top()
// where the stack_name is the name of the stack

Parameter

This function does not require a parameter.

Return value

The stack.top() is used to get the reference of the element at the top of the stack. It does not remove that element from the stack.

Code

#include <iostream>
//header file
#include <stack>
using namespace std;
int main() {
//filled stack
stack<int> stack1;
stack1.push(0);
stack1.push(2);
stack1.push(5);
stack1.push(3);
stack1.push(1);
//stack1 = 1->3->5->2->0
cout<<"The top element of stack1: \n"<<stack1.top()<<"\n";
}

RELATED TAGS

c++
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring