次の方法で共有


Visual C++ で stack::top 関数と stack::empty STL 関数を使用する

この記事では、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;

Note

プロトタイプのクラス名またはパラメーター名が、ヘッダー ファイルのバージョンと一致しない可能性があります。 読みやすさを向上させるために変更されたものもあります。

stack::top 関数と stack::empty 関数の説明

top関数は、スタックの最上位要素を返します。 top関数を呼び出す前に、スタックに 1 つ以上の要素があることを確認する必要があります。 top関数の最初のバージョンでは、スタックの先頭の要素への参照が返され、値を変更できます。 2 番目の関数は定数参照を返し、スタックを誤って変更しないようにします。

empty関数は、スタックに要素がない場合true を返します。 1 つ以上の要素がある場合、関数は 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();
    }
}