const関数でメンバ関数のコンテナ関数を扱うとき、そのままでは扱うことができない。
例えば
class hoge {
public:
std::string GetValue(int key) const;
private:
std::map<int, std::string> keyvaluemap;
};
std::string hoge::GetValue(int key) const {
return keyvaluemap[key];
}
上記のソースコードは、GetValue関数内でコンパイルエラーが発生する。
どうもコンテナは[]でアクセスすると格納されている値のコピーを作成するらしい。
下記のようにソースコードを書き換えると回避できるようだ。
std::string hoge::GetValue(int key) const {
std::map<int, std::string>::const_iterator itr;
itr = keyvaluemap.find(key);
return itr->second;
}
10/10追加
上記のようなめんどくさい方法を取らなくても、以下の方法で取得できるようだ。
std::string hoge::GetValue(int key) const {
return keyvaluemap.at(key);
}