Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end called the top of the stack and an element is removed from the same end only.
stack::top() top() function is used to reference the top(or the newest) element of the stack.
Parameters : No value is needed to pass as the parameter.
Return Value: Direct reference to the top element of the stack container.
Input : stackname.push(5); stackname.push(1); stackname.top(); Output : 1 Input : stackname.push(5); stackname.push(1); stackname.push(2); stackname.top(); Output : 2
Errors and Exceptions
- If the stack container is empty, it causes undefined behaviour
- It has a no exception throw guarantee if the stack is not empty
Given a stack of integers, find the sum of the all the integers.
Input : 1, 8, 3, 6, 2 Output: 20
- Check if the stack is empty, if not add the top element to a variable initialised as 0, and pop the top element.
- Repeat this step until the stack is empty.
- Print the final value of the variable.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- stack empty() and stack size() in C++ STL
- Sort a stack using a temporary stack
- Stack in C++ STL
- stack swap() in C++ STL
- stack push() and pop() in C++ STL
- stack emplace() in C++ STL
- Stack of Pair in C++ STL with Examples
- priority_queue::top() in C++ STL
- Stack Unwinding in C++
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Heap overflow and Stack overflow
- Delete middle element of a stack
- Level order traversal in spiral form | Using one stack and one queue
- Sudo Placement[1.3] | Stack Design
- Check if the elements of stack are pairwise sorted
- Level order traversal in spiral form using stack and multimap
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Sort a stack using recursion
- Top 10 Programming Languages for Blockchain Development
- Top 5 IDEs for C++ That You Should Try Once
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Vik_24