stack::top

返回对元素位于堆栈顶部。

reference top( );
const_reference top( ) const;

返回值

为最后一个元素的引用在容器位于堆栈顶部。

备注

堆栈必须是非空应用成员函数。 堆栈顶部为最近添加的元素占据的该位置是最后一个元素在容器的末尾。

如果 top 的返回值赋给 const_reference,不能修改堆栈对象。 如果 top 的返回值赋给 reference,可以修改堆栈对象。

示例

// stack_top.cpp
// compile with: /EHsc
#include <stack>
#include <iostream>

int main( )
{
   using namespace std;
   stack <int> s1;
   
   s1.push( 1 );
   s1.push( 2 );

   int& i = s1.top( );
   const int& ii = s1.top( );

   cout << "The top integer of the stack s1 is "
        << i << "." << endl;
   i--;
   cout << "The next integer down is "<< ii << "." << endl;
}
  
  

要求

标头: <stack>

命名空间: std

请参见

参考

stack Class

stack::top 和 stack::empty

标准模板库