Поделиться через


Используйте map::end, map::find, map::insert, map::iterator и map::value_type функции STL в Visual C++

В этой статье показано, как использовать map::endсимволы , map::findи map::insertmap::iteratormap::value_type стандартные символы библиотеки шаблонов (STL) в Visual C++.

Исходная версия продукта: Visual C++
Исходный номер базы знаний: 157159

Обязательный заголовок

<map>

Прототипы

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);

Примечание.

Имена классов и параметров в прототипах могут не совпадать с версией в файле заголовка. Некоторые из них были изменены, чтобы улучшить удобочитаемость.

Description

Функция end() возвращает итератор, указывающий один за конец последовательности.

Find возвращает итератор, который выбирает первый элемент, ключ сортировки которого равен ключу сортировки key. Если такой элемент не существует, итератор равен end().

Если ключ еще не существует, insert добавьте его в последовательность и возвратит pair<iterator, true>. Если ключ уже существует, insert не добавляет его в последовательность и возвращается pair <iterator, false>.

В следующем примере создается карта инттов с строками. В этом случае сопоставление состоит из цифр в их строковые эквиваленты (1 —> Один, 2 —> Два и т. д.).

Программа считывает число от пользователя, находит слово эквивалентно для каждой цифры (с помощью карты) и выводит число обратно в виде ряда слов. Например, если пользователь вводит 25463, программа отвечает: два пяти четырех шести трех.

Пример кода

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

Выходные данные программы:

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

Ссылки

Для получения одинаковых сведений о map::endкартах, map::findа map::insertтакже посетите карту::insert, map::find и map::end.