目录

stack::top

描述 (Description)

C ++函数std::stack::top()返回堆栈的顶部元素。 这是执行弹出操作后删除的元素。

声明 (Declaration)

以下是std :: stack :: top()函数形式std :: stack标头的声明。

C++98

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

C++11

reference& top();
const_reference& top() const;

参数 (Parameters)

没有

返回值

返回堆栈的顶部元素。

异常 (Exceptions)

取决于底层容器。

时间复杂

常数即O(1)

例子 (Example)

以下示例显示了std :: stack :: top()函数的用法。

#include <iostream>
#include <stack>
using namespace std;
int main(void) {
   stack<int> s;
   for (int i = 0; i < 5; ++i)
      s.emplace(i + 1);
   while (!s.empty()) {
      cout << s.top() << endl;
      s.pop();
   }
   return 0;
}

让我们编译并运行上面的程序,这将产生以下结果 -

Stack contents are
5
4
3
2
1
↑回到顶部↑
WIKI教程 @2018