stack::top 和 stack::empty
在 Visual C++ 演示如何使用 堆栈:: 顶级 和 堆栈:: null STL 功能。
template<class _TYPE, class _C, class _A>
value_type& stack::top( );
template<class _TYPE, class _C, class _A>
const value_type& stack::top( ) const;
template<class _TYPE, class _C, class _A>
bool stack::empty( ) const;
备注
备注
类/参数名在原型不匹配版本在头文件。修改某些提高可读性。
顶级 函数返回堆栈中最顶层的元素。 应确保堆栈上存在一个或多个元素在调用顶部的功能之前。 顶部的函数的第一个版本返回对堆栈顶部的元素,可以修改此值。 第二个函数返回常数引用,确保不会意外修改堆栈。 ; 如果在堆栈的元素,该空函数返回 true 。 如果有一个或多个元素,函数返回 错误。 您应使用 null 的功能验证与堆栈上的元素在调用顶部的功能之前。
示例
// StackTopEmpty.cpp
// compile with: /EHsc
// Illustrates how to use the top function to
// retrieve the last element of the controlled
// sequence. It also illustrates how to use the
// empty function to loop though the stack.
//
// Functions:
//
// top : returns the top element of the stack.
// empty : returns true if the stack has 0 elements.
//////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <stack>
#include <iostream>
using namespace std ;
typedef stack<int> STACK_INT;
int main()
{
STACK_INT stack1;
cout << "stack1.empty() returned " <<
(stack1.empty()? "true": "false") << endl; // Function 3
cout << "stack1.push(2)" << endl;
stack1.push(2);
if (!stack1.empty()) // Function 3
cout << "stack1.top() returned " <<
stack1.top() << endl; // Function 1
cout << "stack1.push(5)" << endl;
stack1.push(5);
if (!stack1.empty()) // Function 3
cout << "stack1.top() returned " <<
stack1.top() << endl; // Function 1
cout << "stack1.push(11)" << endl;
stack1.push(11);
if (!stack1.empty()) // Function 3
cout << "stack1.top() returned " <<
stack1.top() << endl; // Function 1
// Modify the top item. Set it to 6.
if (!stack1.empty()) { // Function 3
cout << "stack1.top()=6;" << endl;
stack1.top()=6; // Function 1
}
// Repeat until stack is empty
while (!stack1.empty()) { // Function 3
const int& t=stack1.top(); // Function 2
cout << "stack1.top() returned " << t << endl;
cout << "stack1.pop()" << endl;
stack1.pop();
}
}
要求
标题: stack