辞書型
pythonのコードを見ているとこんなのが出て来た。
辞書型
obj_scales = {'feature_1': 0.1,
'feature_2': 0.2,
'feature_3': 0.4,
'feature_4': 0.8
}
辞書型と言うらしい。こんな風に使うらしい。
Python
obj_scales['feature_3']
#0.4を返す
仕組みは簡単でC++でシコシコ作っても何とかなりそうだが、デバッグするとき見た目がオリジナルと全然違うのはなあ、と探していたら最近のC++には辞書型があるらしい。
↓詳しい説明に感謝。
これであっさり解決である。型といってもテンプレートである。
C++
std::map<std::string, int> obj_scales = {
{"feature_1", 0.1 },
{"feature_2", 0.2 },
{"feature_3", 0.4 },
{"feature_4", 0.8 }
};
解決解決と思っていたらこんなのが出て来た。
Python
map_dims = {'feature_1': [40,32],
'feature_2': [20,16],
'feature_3': [10,8],
'feature_4': [5,4]
}
intの所を配列で定義すればいいのか?
C++
std::map<std::string, int[2]> map_dims ={
{"feature_1",{40,32}},
{"feature_2",{20,16}},
{"feature_3",{10, 8}},
{"feature_4",{5, 4}}
};
//エラー
だめかー。
「E0289 コンストラクター "std::map<_Kty, _Ty, _Pr, _Alloc>::map [代入_Kty=std::string, _Ty=int [2], _Pr=std::less, _Alloc=std::allocator>]" のインスタンスが引数リストと一致しません」
C++
std::map<const std::string, int*> fmap_dims = {
{"feature_1",{40,32}},
{"feature_2",{20,16}},
{"feature_3",{10, 8}},
{"feature_4",{5, 4}}
};
//エラー
std::map<const std::string, int[]> fmap_dims = {
{"feature_1",{40,32}},
{"feature_2",{20,16}},
{"feature_3",{10, 8}},
{"feature_4",{5, 4}}
};
//エラー
困った時のGoogle先生だが参考になる解決策が無さそう。英語(std::map array)で検索してみると、そのものずばりが出てきた。
上の記事によると要するにmapの要素に配列はダメで、配列のポインタ、もしくは構造体を定義しろと言う事らしい。
C++
int _x1[2] = { 40, 32 };
int _x2[2] = { 20, 16 };
int _x3[2] = { 10, 8 };
int _x4[2] = { 5, 4 };
std::map<const std::string, int(*)[2]> fmap_dims = {
{"feature_1",&_x1},
{"feature_2",&_x2},
{"feature_3",&_x3},
{"feature_4",&_x4}
};
これで通った。変数を別に定義するのは面倒くさいが今のところこれがPythonのオリジナルコードに近い。