C++ Stack top()函数返回堆栈中top元素的值。最上面的元素是最近添加到堆栈中的元素。最后添加的元素是顶部元素。在堆栈中存在的所有元素中,顶部元素脱颖而出,并且更为重要,因为堆栈上的所有主要操作都在顶部元素中执行。无论是推,弹出还是其他所有操作,都在最高位置完成。
value_type& top(); const value_type& top() const;
该函数仅用于返回top元素的值,因此不带任何参数。函数的返回类型基于堆栈的值类型。
该函数返回堆栈的顶部元素。
//程序说明了堆栈中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()函数的使用,以检索最上面的元素的值。
#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()函数的使用,以检索最上面的元素的值。
#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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)