C++ Stack 中的 top函数

首页 / C++入门教程 / C++ Stack 中的 top函数

C++ Stack top()函数返回堆栈中top元素的值。最上面的元素是最近添加到堆栈中的元素。最后添加的元素是顶部元素。在堆栈中存在的所有元素中,顶部元素脱颖而出,并且更为重要,因为堆栈上的所有主要操作都在顶部元素中执行。无论是推,弹出还是其他所有操作,都在最高位置完成。

top - 语法

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

top - 参数

该函数仅用于返回top元素的值,因此不带任何参数。函数的返回类型基于堆栈的值类型。

top - 返回值

该函数返回堆栈的顶部元素。

无涯教程网

top - 例子1

//程序说明了堆栈中top()函数的使用,以检索最上面的元素的值。

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

输出:

newstack.top() is modified to 100

top - 例子2

//程序说明了堆栈中top()函数的使用,以检索最上面的元素的值。

#include <iostream>
#include <stack>
using namespace std;
int main()
{
	int result = 0;
	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;
}

输出:

21

top - 例子3

//程序说明了堆栈中top()函数的使用,以检索最上面的元素的值。

#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;
}

输出:

newstack.top() is 14

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

赵成的运维体系管理课 -〔赵成〕

Linux实战技能100讲 -〔尹会生〕

黄勇的OKR实战笔记 -〔黄勇〕

Electron开发实战 -〔邓耀龙〕

Redis核心技术与实战 -〔蒋德钧〕

Spark性能调优实战 -〔吴磊〕

编程高手必学的内存知识 -〔海纳〕

结构思考力 · 透过结构看问题解决 -〔李忠秋〕

工程师个人发展指南 -〔李云〕

好记忆不如烂笔头。留下您的足迹吧 :)