首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::stack::top

reference top();

const_reference top() const;

返回对堆栈中顶部元素的引用。这是最近推出的元素。调用时将删除此元素。pop().有效地打电话c.back()...

参数

%280%29

返回值

引用最后一个元素。

复杂性

常量。

二次

代码语言:javascript
复制
#include <stack>
#include <iostream>
 
int main()
{
    std::stack<int>   s;
 
    s.push( 2 );
    s.push( 6 );
    s.push( 51 );
 
    std::cout << s.size() << " elements on stack\n";
    std::cout << "Top element: "
              << s.top()         // Leaves element on stack
              << "\n";
    std::cout << s.size() << " elements on stack\n";
    s.pop();
    std::cout << s.size() << " elements on stack\n";
    std::cout << "Top element: " << s.top() << "\n";
 
    return 0;
}

二次

产出:

二次

代码语言:javascript
复制
3 elements on stack
Top element: 51
3 elements on stack
2 elements on stack
Top element: 6

二次

另见

push

inserts element at the top (public member function)

pop

removes the top element (public member function)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券