The stack.top()
function in C++ is used to get the reference of the element at the top of the stack.
The following illustration shows a visual representation of the stack.top()
function.
In order to use the stack.top()
function, we must include stack
in the program, as shown below:
#include <stack>
stack_name.top()
// where the stack_name is the name of the stack
This function does not require a parameter.
The stack.top()
is used to get the reference of the element at the top of the stack. It does not remove that element from the stack.
#include <iostream>//header file#include <stack>using namespace std;int main() {//filled stackstack<int> stack1;stack1.push(0);stack1.push(2);stack1.push(5);stack1.push(3);stack1.push(1);//stack1 = 1->3->5->2->0cout<<"The top element of stack1: \n"<<stack1.top()<<"\n";}