constのstd::mapに対してoperator[]を呼び出すとコンパイルエラー

constのstd::mapに対してoperator[]を呼び出すとコンパイルエラーになる

int f(const std::map<int, int>& m, int x) {
  return m[x]; //=>コンパイルエラー
}

std::mapのoperator[]は次のように定義されていて、constメソッドではない。

Ty& operator[](const Key& keyval);

C++11ではat()メンバ関数がstd::mapに追加された。

次のようにコードを記述できる。

int f(const std::map<int, int>& m, int x) {
  return m.at(x);
}

ちなみに、C++Builder XE5の64ビットコンパイラはC++11に対応しているが、32ビットコンパイラは対応していない。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください