次の方法で共有


map::insert, map::find, と map::end

マップの使い方を示しています:: insertmap, :: 検索,および割り当て:: Visual C++ の端度器テンプレート (STL) ライブラリ関数。

iterator map::end( ); 
iterator map::find(
   const Key& Key
);
pair<iterator, bool> 
map::insert(
   const value_type& x
);

解説

[!メモ]

プロトタイプのクラスやパラメーター名はヘッダー ファイルのバージョンと一致しない。ただし読みやすさが向上するように変更されました。

終了 関数の戻り値反復子シーケンスの末尾より後ろのそのポイント 1。 検索 並べ替えキーの キー は最初の要素を指定する反復子を返します。そのような要素が存在しない場合反復子は 終了 になります。キーが存在しない場合は 挿入 はシーケンス戻り pair< 反復子 true> に追加します。キーが既に存在する場合は 挿入 はシーケンスに追加せずpair < 反復子 False> を返しません。次の例では 文字列 . に intのマップを作成します。この場合マッピングは数字の文字列と (1 ~ > 「 1 」" 2 - > 「 2 」など)。プログラムはユーザーの数を検出された数値に対してマップ () を使用して一連の単語として印刷を同じ数の単語読み取ります。たとえばユーザーが 25463 を入力するとプログラムはで応答 : 2 5 4 6 3。

使用例

// map_insert_find_end.cpp
// compile with: /EHsc
#pragma warning(disable:4786)
#include <iostream>
#include <string>
#include <map>

using namespace std;

typedef map<int, string, less<int> > INT2STRING;

int main()
{
   // 1. Create a map of ints to strings
   INT2STRING theMap;
   INT2STRING::iterator theIterator;
   string theString = "";
   unsigned 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;
   }
}

入力

12
q

出力例

Enter "q" to quit, or enter a Number: 12
One Two
Enter "q" to quit, or enter a Number: q

必要条件

ヘッダー : <map>

参照

概念

標準テンプレート ライブラリのサンプル