2013年11月27日水曜日

std::mapってなに

久しぶりの投稿。
cocos2dの勉強を始めたので、それを機に備忘録的に勉強内容を書いていこうと思う。

stdとは、C++の標準ライブラリのnamespace。

std::map<>が出てきたのでその使い方を覚えたい。
mapはキーと値との組み合わせでによって管理するコンテナらしい。
使いこなせばJSの連想配列的な使い方出来て便利そう。

使い方

#include <map>
#include <string>
#include <iostream>

int main()
{
 using namespace std;

 // 宣言
 map<int string=""> names;  // キーがint、値がchar*のmap

 // 要素を追加する
 names.insert( map<int string="">::value_type( 10, "aaa" ) );
 names.insert( map<int string="">::value_type( 30, "ccc" ) );
 names.insert( map<int string="">::value_type( 50, "eee" ) );
 names.insert( map<int string="">::value_type( 40, "ddd" ) );
 names.insert( map<int string="">::value_type( 20, "bbb" ) );

 // 値を変更
 names[50] = "fff";
 
 // 要素を出力する
 cout << names[10] << endl;
 cout << names[20] << endl;
 cout << names[30] << endl;
 cout << names[40] << endl;
 cout << names[50] << endl;

 return 0;
}