c++のmapの初期化の方法を調べたので記述します。
配列を初期化するときに要素を一気に生成(以下のコード)できますが、「mapで同じことができないのか?」という疑問から調べてみました。
以下、配列の初期化のサンプルコードです。
# include <stdio.h>
int main()
{
int ary[] = {1, 2, 4, 8, 16, 32, 64, 128};
for(int cnt = 0 ; cnt < sizeof(ary) / sizeof(ary[0]) ; cnt++)
printf("ary[%d] = %d\n" , cnt , ary[cnt]);
return 0;
}
調べたところ、以下のようにすれば、mapも同じように初期化できるようです。
# include <stdio.h>
# include "map"
int main()
{
std::map<int, const char*> mapList =
{
{1, "a"},
{2, "b"},
{3, "c"},
};
std::map<int, const char*>::iterator it = mapList.begin();
while(it != mapList.end())
{
printf("key:%d value:%s\n" , it->first , it->second);
it++;
}
return 0;
}
注意点としては、C++11で追加された機能であるということです。C++11より前のバージョンでは上の書き方はできないのでご注意ください。