C++ mapのconstアクセッサ
C++ map
クラスのoperator[]
はconstではない
C++のmap
クラスでoperator[]
はconstバージョンが提供されていないので、constなメンバ関数で上記オペレータを用いてアクセスしようとするとコンパイルエラーとなってしまいます。C++11以降ではat()
関数が提供されていますので、それを使いましょう。C++11以前では … find()
で検索して値を返すしかないのかな?…
#include <iostream> #include <map> #include <vector> class ConstTest { public: ConstTest() : int_vec({0, 1, 2, 3}), int_map({{"ichi", 1}, {"ni", 2}, {"san", 3}}) {} int GetVector(int idx) const { return int_vec[idx]; } int GetMap(const std::string& key) const { // return int_map[key]; # これはNG return int_map.at(key); } private: std::vector<int> int_vec; std::map<std::string, int> int_map; }; int main() { ConstTest t_class; std::cout << t_class.GetVector(1) << std::endl; std::cout << t_class.GetMap("san") << std::endl; return 0; }
上のコードで、ついvector
と同じように[]
オペレータを使ってしまうとコンパイルエラーとなってしまいます。
map
の[]
がconst
となっていないのは、Keyが存在しなかった場合に、新しい要素を自動で追加するからです。それに対して、at()
の場合はstd::out_of_range
例外が投げられます
最近のコメント