std::stack<T,Container>::top
来自 cppreference.cn
reference top(); |
(1) | |
const_reference top() const; |
(2) | |
返回栈顶元素的引用。这是最近被推入的元素。此元素将在调用 pop() 时被移除。等效于: c
.back()。
目录 |
[编辑] 参数
(无)
[编辑] 返回值
对最后一个元素的引用。
[编辑] 复杂度
常数。
[编辑] 示例
运行此代码
#include <iostream> #include <stack> void reportStackSize(const std::stack<int>& s) { std::cout << s.size() << " elements on stack\n"; } void reportStackTop(const std::stack<int>& s) { // Leaves element on stack std::cout << "Top element: " << s.top() << '\n'; } int main() { std::stack<int> s; s.push(2); s.push(6); s.push(51); reportStackSize(s); reportStackTop(s); reportStackSize(s); s.pop(); reportStackSize(s); reportStackTop(s); }
输出
3 elements on stack Top element: 51 3 elements on stack 2 elements on stack Top element: 6
[编辑] 参见
在顶部插入元素 (公共成员函数) | |
移除顶部元素 (公共成员函数) |