How to Access the Top Element of a Stack in C++? Last Updated : 23 Jul, 2025 Comments Improve Suggest changes Like Article Like Report In C++, The stack is a container adapter that provides a Last-In-First-Out (LIFO) type of data structure in which insertion and deletion are done at the end only. In this article, we will learn how to access the top element of a stack in C++. Example: Input: myStack = {10, 20, 30, 40} Output: Top Element: 40Find the Top Element of a Stack in C++To access the top element of a stack in C++, we can use the std::stack::top() function that retrieves the top element of the stack (if the stack is not empty). This function is mainly used to reference the top element of the stack. C++ Program to Access the Top Element of a Stack C++ // C++ Program to illustrate how to access the top element // of the stack #include <iostream> #include <stack> using namespace std; // Driver code int main() { // Creating a stack of integers stack<int> stackData; // Pushing elements onto the stack stackData.push(10); stackData.push(20); stackData.push(30); stackData.push(40); // Accessing the top element of the stack using top() int res = stackData.top(); // Printing the top element cout << "Top Element: " << res << endl; // Printing the stack cout << "Stack Elements: "; while (!stackData.empty()) { cout << stackData.top() << " "; stackData.pop(); } cout << endl; return 0; } OutputTop Element: 40 Stack Elements: 40 30 20 10 Time Complexity: O(1)Auxiliary Space: O(1) Create Quiz Comment G gauravggeeksforgeeks Follow 0 Improve G gauravggeeksforgeeks Follow 0 Improve Article Tags : C++ Programs C++ STL cpp-stack CPP Examples +1 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 Like