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:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
stack<int> st;
st.push(5);
st.push(11);
cout << st.top() << endl;
st.push(9);
cout << st.top();
return 0;
}
stack::top() Syntax
st.top()
where st is the name of std::stack.
ParametersThe following examples demonstrates the use of stack::top() function in different scenarios:
Example 1: Finding Top Element of Stack after Pop Operation C++
// C++ Program to illustrate the use of
// stcak::top()
#include <bits/stdc++.h>
using namespace std;
int main() {
stack<int> st;
st.push(5);
st.push(11);
st.push(9);
// Top element before pop
cout << st.top() << endl;
// Popping the top element
st.pop();
cout << st.top();
return 0;
}
Example 2: Tyring to Find Top Element of Empty Stack C++
// C++ Program to illustrate the use of
// stcak::top()
#include <bits/stdc++.h>
using namespace std;
int main() {
// Empty stack
stack<int> st;
// Top element of empty stack
cout << st.top();
return 0;
}
Output
Undefined behaviour
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4