名稱空間
變體
操作

std::stack<T,Container>::top

來自 cppreference.com
< cpp‎ | 容器‎ |
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

[編輯] 參閱

在棧頂插入元素
(公共成員函式) [編輯]
移除頂部元素
(公共成員函式) [編輯]