English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and Example of Stack top() Function

C++ STL Stack (Stack)

C ++ The function of the Stack top() is to: return the value of the top element. The top element is the most recently added element to the stack. The last added element is the top element. The top element is the most prominent and important among all the elements that appear in the stack, because all the main operations on the stack are executed on the top element. Whether it is push, pop, or other operations, all operations are completed at the top position.

Syntax

value_type& top();
const value_type& top() const;

Parameter

This function is used only to return the value of the top element, so it does not take any parameters. The return type of the function is based on the value type of the stack.

Return Value

This function returns the top element of the stack.

Instance1

//This program demonstrates the use of the top() function in a stack to retrieve the value of the topmost element.

#include <iostream>
#include <stack>
int main()
{
	std::stack<int> newstack;
	newstack.push(24);
	newstack.push(80);
	newstack.top() +=20;
	std::cout << "newstack.top() modified to " << newstack.top()();
	return 0;
}

Output:

Modify newstack.top() to 100

Instance2

//This program demonstrates the use of the top() function in a stack to retrieve the value of the topmost element.

#include <iostream>
#include <stack>
using namespace std;
int main()
{
	int result = 0;
	std::stack<int> newstack;
	newstack.push(2);
	newstack.push(7);
	newstack.push(4);
	newstack.push(5);
	newstack.push(3);
	while(!newstack.empty())
	{
	   result = result + newstack.top();
	   newstack.pop();
	}
	cout << result;
	return 0;
}

Output:

21

Instance3

//This program demonstrates the use of the top() function in a stack to retrieve the value of the topmost element.

#include <iostream>      
#include <stack>          
int main ()
{
  std::stack<int> newstack;
  newstack.push(9);
  newstack.push(14);
   std::cout << "newstack.top() is " << newstack.top() << '\n';
  return 0;
}

Output:

newstack.top() is 14

Complex

The complexity of the function is constant. The function retrieves the value of the top element without incurring any additional time or space.

Data Races

This function accesses the container and retrieves the last inserted element. It provides the top element of the stack.

Exception Safety

Guarantees equivalent operations to those performed on the underlying container objects.

C++ STL Stack (Stack)