本文演示如何在 Visual C++ 中使用 stack::top 和 stack::empty STL 函数。 本文中的信息仅适用于非托管的 Visual C++ 代码。
原始产品版本: Visual C++
原始 KB 数: 158040
必需的标头
<stack>
原型
template <class _TYPE, class _C, class _A> // Function 1
value_type &stack::top();
template <class _TYPE, class _C, class _A> // Function 2
const value_type &stack::top() const;
template <class _TYPE, class _C, class _A> // Function 3
bool stack::empty() const;
注意
原型中的类或参数名称可能与头文件中的版本不匹配。 一些已修改以提高可读性。
stack::top 和 stack::empty 函数的说明
该 top 函数返回堆栈的最顶层元素。 在调用 top 函数之前,应确保堆栈上有一个或多个元素。 函数的第一个版本 top 返回对堆栈顶部元素的引用,使你可以修改值。 第二个函数返回常量引用,确保不会意外修改堆栈。
如果堆栈中没有元素,该 empty 函数将 返回 true 。 如果有一个或多个元素,该函数将返回 false。 在调用top函数之前,应使用该empty函数来验证堆栈上是否存在元素。
代码示例
//////////////////////////////////////////////////////////////////////
// Compile options needed: /GX
// StackTop&Empty.cpp : 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.
// Copyright (c) 1996 Microsoft Corporation. All rights reserved.
//////////////////////////////////////////////////////////////////////
#pragma warning(disable : 4786)
#include <stack>
#include <iostream>
#if _MSC_VER > 1020 // if VC++ version is > 4.2
using namespace std; // std c++ libs implemented in std
#endif
typedef stack<int, deque<int>> STACK_INT;
void 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();
}
}