C++ stack top() function

C++ Stack top() function returns the value of the top element in the stack. The top element is the one which was recently added on the stack. The last added element is the top element. Of all the elements that are present in a stack the top element stands out and is more significant as all the major operations on the stack are performed at the top element. Be it push, pop or anything all the operations are done at the top most position.

Syntax

Parameters

The function is used only for returning the value of the top element and hence takes nothing as parameters. The return type of the function is based on the value type of the stack.

Return value

The function returns the top element of the stack.

Example 1

//The program illustrates the use of top() function in stack to retrieve the value of top most element.

Output:

newstack.top() is modified to 100

Example 2

//The program illustrates the use of top() function in stack to retrieve the value of top most element.

Output:

21

Example 3

//The program illustrates the use of top() function in stack to retrieve the value of top most element.

Output:

newstack.top() is 14

Complexity

The complexity of the function is constant. The function only retrieves the value of the top element and does not take any extra time or space.

Data races

The function accesses the container, and retrieves the element which was last inserted. The top most element of the stack is given.

Exception Safety

Guarantee as equivalent to the operations that are performed on the underlying container object is provided.

Next TopicC++ Stack




Latest Courses