Compartilhar via


Usar funções STL stack::top e stack::empty no Visual C++

Este artigo ilustra como usar as stack::top funções e stack::empty STL no Visual C++. As informações neste artigo se aplicam somente ao código Visual C++ não gerenciado.

Versão original do produto: Visual C++
Número original do KB: 158040

Cabeçalho necessário

  • <stack>

Protótipo

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;

Observação

Os nomes de classe ou parâmetro no protótipo podem não corresponder à versão no arquivo de cabeçalho. Alguns foram modificados para melhorar a legibilidade.

Descrição das funções stack::top e stack::empty

A top função retorna o elemento mais alto da pilha. Você deve garantir que haja um ou mais elementos na pilha antes de chamar a top função. A primeira versão da top função retorna uma referência ao elemento do topo da pilha, permitindo que você modifique o valor. A segunda função retorna uma referência constante, garantindo que você não modifique acidentalmente a pilha.

A empty função retornará true se não houver elementos na pilha. Se houver um ou mais elementos, a função retornará false. Você deve usar a empty função para verificar se há elementos restantes na pilha antes de chamar a top função.

Código de exemplo

//////////////////////////////////////////////////////////////////////
// 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();
    }
}