VOOZH about

URL: https://www.geeksforgeeks.org/cpp/stack-top-c-stl/

⇱ stack top() in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

stack top() in C++ STL

Last Updated : 14 Feb, 2025

In C++, the std::stack::top() is used to find the top element of the std::stack container. It is a member function of std::stack class defined inside the <stack> header file. In this article, we will learn how to find the top element of stack using stack::top() in C++.

Example:


Output
11
9

stack::top() Syntax

st.top()

where st is the name of std::stack.

Parameters

  • This function does not take any parameter.

Return Value

  • Return the top element of the stack container.
  • If the stack is empty, its behaviour is undefined.

More Examples of stack::top()

The following examples demonstrates the use of stack::top() function in different scenarios:

Example 1: Finding Top Element of Stack after Pop Operation


Output
9
11

Example 2: Tyring to Find Top Element of Empty Stack


Output

Undefined behaviour
Comment