Compartir a través de


Use las funciones map::end, map::find, map::insert, map::iterator y map::value_type STL en Visual C++

En este artículo se muestra cómo usar los map::endsímbolos , map::find, map::insert, map::iteratory map::value_type biblioteca de plantillas estándar (STL) en Visual C++.

Versión original del producto: Visual C++
Número de KB original: 157159

Encabezado obligatorio

<map>

Prototipos

iterator map::end();

// Key is the data type of template argument #1 for map
iterator map::find(const Key& key);
pair<iterator, bool> map::insert(const value_type& x);

Nota:

Es posible que los nombres de clase o parámetro de los prototipos no coincidan con la versión del archivo de encabezado. Algunas se han modificado para mejorar la legibilidad.

Descripción

La end() función devuelve un iterador que señala uno más allá del final de una secuencia.

Find devuelve un iterador que elige el primer elemento cuya clave de ordenación es igual a key. Si no existe ningún elemento de este tipo, el iterador es igual a end().

Si la clave aún no existe, insert la agregará a la secuencia y devolverá pair<iterator, true>. Si la clave ya existe, insert no la agrega a la secuencia y devuelve pair <iterator, false>.

En el ejemplo siguiente se crea un mapa de ints a cadenas. En este caso, la asignación es de dígitos a sus equivalentes de cadena (1 -> Uno, 2 -> Dos, etc.).

El programa lee un número del usuario, busca la palabra equivalente para cada dígito (mediante el mapa) y vuelve a imprimir el número como una serie de palabras. Por ejemplo, si el usuario escribe 25463, el programa responde con: Two Five Four Six Three.

Código de ejemplo

//////////////////////////////////////////////////////////////////////
// Compile options needed: None
// <filename> : main.cpp
// Functions:
// end
// find
// insert
// of Microsoft Product Support Services,
// Copyright (c) 1996 Microsoft Corporation. All rights reserved.
//////////////////////////////////////////////////////////////////////
// disable warning C4018: '<' : signed/unsigned mismatch
// okay to ignore

#pragma warning(disable: 4018)

#pragma warning(disable:4786)
#include <iostream>
#include <string>
#include <map>
using namespace std;

typedef map<int, string, less<int>, allocator<string> > INT2STRING;
void main()
{
    // 1. Create a map of ints to strings
    INT2STRING theMap;
    INT2STRING::iterator theIterator;
    string theString = "";
    int index;
    // Fill it with the digits 0 - 9, each mapped to its string counterpart
    // Note: value_type is a pair for maps...
    theMap.insert(INT2STRING::value_type(0,"Zero"));
    theMap.insert(INT2STRING::value_type(1,"One"));
    theMap.insert(INT2STRING::value_type(2,"Two"));
    theMap.insert(INT2STRING::value_type(3,"Three"));
    theMap.insert(INT2STRING::value_type(4,"Four"));
    theMap.insert(INT2STRING::value_type(5,"Five"));
    theMap.insert(INT2STRING::value_type(6,"Six"));
    theMap.insert(INT2STRING::value_type(7,"Seven"));
    theMap.insert(INT2STRING::value_type(8,"Eight"));
    theMap.insert(INT2STRING::value_type(9,"Nine"));
    // Read a Number from the user and print it back as words
    for( ; ; )
    {
       cout << "Enter \"q\" to quit, or enter a Number: ";
       cin >> theString;
       if(theString == "q")
           break;
       // extract each digit from the string, find its corresponding
       // entry in the map (the word equivalent) and print it
       for(index = 0; index < theString.length(); index++){
           theIterator = theMap.find(theString[index] - '0');
           if(theIterator != theMap.end()) // is 0 - 9
               cout << (*theIterator).second << " ";
           else // some character other than 0 - 9
               cout << "[err] ";
       }
       cout << endl;
    }
}

Salida del programa:

Enter "q" to quit, or enter a Number: 22
Two Two
Enter "q" to quit, or enter a Number: 33
Three Three
Enter "q" to quit, or enter a Number: 456
Four Five Six
Enter "q" to quit, or enter a Number: q

Referencias

Para obtener la misma información sobre map::end, map::findy map::insert, visite map::insert, map::find y map::end.