LoginSignup
0
0

More than 5 years have passed since last update.

const関数でコンテナを扱う場合の注意【個人用備忘録】

Last updated at Posted at 2013-10-07

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);
}
0
0
7

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0