Share via


stack::size (STL Samples)

Muestra cómo utilizar la función de biblioteca de (STL) plantillas estándar de pila:: tamaño en Visual C++.

template<class _TYPE, class _C, class _A>
   size_type stack::size( ) const;

Comentarios

[!NOTA]

La clase y los nombres de parámetro en el prototipo no coincide con la versión del archivo de encabezado.Algunos se han modificado para mejorar la legibilidad.

la función de stack::size devuelve el número de elementos en la pila.Es aceptable llamar a esta función con una pila vacía; devolverá un valor de 0.

Ejemplo

// StackSize.cpp
// compile with: /EHsc
// Illustrates how to use the size function to determine
// the number of elements on the stack.
//
// Functions:
//
//    size :  returns the number of elements in the stack.
//////////////////////////////////////////////////////////////////////

#pragma warning(disable:4786)
#include <stack>
#include <string>
#include <iostream>

using namespace std ;

typedef stack<string> STACK_STRING;

int main()
{
   STACK_STRING stack1;

   // Check the size of an empty stack. Should return 0.
   cout << "stack1.size() equals " << stack1.size() << endl;

   // Add item "Hello" to Stack1.
   cout << "stack1.push('Hello')" << endl;
   stack1.push("Hello");

   // Add item "This is the second element" to Stack1.
   cout << "stack1.push('This is the second element')" << endl;
   stack1.push("This is the second element");

   // Check the size of Stack1. Should return 2.
   cout << "stack1.size() equals " << stack1.size() << endl << endl;

   // Add item "Third element" to Stack1.
   cout << "stack1.push('Third element')" << endl;
   stack1.push("Third element");

   // Check the size of Stack1. Should return 3.
   cout << "stack1.size() equals " << stack1.size() << endl << endl;

   // Pop "Third element".
   cout << "stack1.pop()" << endl;
   stack1.pop();

   // Pop "This is the second element".
   cout << "stack1.pop()" << endl;
   stack1.pop();

   // Check the size of Stack1 again. Should return 1.
   cout << "stack1.size() equals " << stack1.size()  << endl << endl;

   // Pop "Hello".
   cout << "stack1.pop()" << endl;
   stack1.pop();

   // Check the size of Stack1. Should return 0.
   cout << "stack1.size() equals " << stack1.size() << endl;
}

Output

stack1.size() equals 0
stack1.push('Hello')
stack1.push('This is the second element')
stack1.size() equals 2

stack1.push('Third element')
stack1.size() equals 3

stack1.pop()
stack1.pop()
stack1.size() equals 1

stack1.pop()
stack1.size() equals 0

Requisitos

encabezado: <pila>

Vea también

Conceptos

Ejemplos de biblioteca de plantillas estándar