C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ stack top()

C++ stack top()函数

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

语法

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

参数

该函数仅用于返回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

示例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

示例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

复杂度

函数的复杂度是恒定的。该函数仅检索top元素的值,而不花费任何额外的时间或空间。

数据竞争

该函数访问容器并检索最后插入的元素。

异常安全

提供与在基础容器对象上执行的操作等效的保证。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4