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:
#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;
}
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
// 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;
}
Output
9 11
Example 2: Tyring to Find Top Element of Empty Stack
// 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