stack::top 和 stack::empty
說明如何使用 stack::top 和 stack::empty STL Visual C++ 中的函式。
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 如果堆疊中沒有任何項目。如果有一或多個項目,此函式會傳回 ,則為 false。您應該使用空白的函式,以確認沒有堆疊上留下前呼叫的最上層的函式的項目。
範例
// 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>