stack top() in C++ STL Last Updated : 14 Feb, 2025 Suggest changes Share 60 Likes Like Report 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; } Output11 9stack::top() Syntaxst.top()where st is the name of std::stack.ParametersThis function does not take any parameter.Return ValueReturn 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++ // 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; } Output9 11Example 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; } OutputUndefined behaviour A AyushSaxena Follow 60 Article Tags : Misc C++ STL CPP-Library cpp-containers-library cpp-stack cpp-stack-functions +3 More Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read My Profile ${profileImgHtml} My Profile Edit Profile My Courses Join Community Transactions Logout Like