本文說明如何在Visual C++中使用 stack::top 和 stack::empty STL 函式。 本文中的資訊僅適用於 Unmanaged 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。 您應該使用 函 empty 式來確認堆疊上還剩元素,再呼叫 函 top 式。
範例指令碼
//////////////////////////////////////////////////////////////////////
// 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();
}
}