map

mapは連想コンテナの一種で、キーと値のペアを保存します。要素はソートされ、キーは重複できません。

mapの書式は次のとおりです。


  #include <map>
  map<type>
  

次の例は、mapを使って整数(int)と文字型(char)の値のペアを保存する例です。


    #include <iostream>
#include <map>

using namespace std;

int main(int argc, char* argv[])
{
   typedef map< int, char > mis;
   mis aMap;
   
   aMap.insert( mis::value_type( 5, 'e' ) );
   aMap.insert( mis::value_type( 3, 'c' ) );
   aMap.insert( mis::value_type( 1, 'a' ) );
   aMap.insert( mis::value_type( 26, 'z' ) );
   aMap.insert( mis::value_type( 2, 'b' ) );
   cout << "サイズ=" << aMap.size() << endl;
   mis::const_iterator iter;
   for (iter = aMap.begin(); iter != aMap.end(); ++ iter)
   {
      cout << (*iter).first << " -> ";
      cout << (*iter).second << endl;
   }
   return 0;
}
  

実行結果は次のようになります。


    サイズ=5
    1 -> a
    2 -> b
    3 -> c
    5 -> e
    26 -> z
  

関連項目

deque

multimap


コンテナ目次 C++目次 inserted by FC2 system