3

次のコードに混乱しています。なぜ正常にコンパイルできないのですか?

class Test { 
public:
  int GetValue( int key ) const
  {
      return testMap[key];
  }

  map<const int, const int> testMap; 
};

常にコンパイル エラーが発生します。

error C2678: binary '[': no ​​operator found which takes "const std :: map <_Kty,_Ty>" type of the left operand operator (or there is no acceptable conversion).

const 修飾子をどこにでも配置しようとしましたが、それでも合格できませんでした。理由を教えてください。

4

2 に答える 2

6

operator[]指定されたキーを持つ要素がconstまだ存在しない場合、要素を挿入するためです。find()にはconstオーバーロードがあるため、インスタンスまたは参照またはポインターを介して呼び出すことができます。constconst

C++11 にはstd::map::at()、境界チェックを追加し、指定されたキーを持つ要素が存在しない場合に例外を発生させる があります。だからあなたは言うことができます

class Test { 
public:
  int GetValue( int key ) const
  {
      return testMap.at(key);
  }

  std::map<const int, const int> testMap; 
};

それ以外の場合は、次を使用しますfind()

  int GetValue( int key ) const
  {
    auto it = testMap.find(key);
    if (it != testMap.end()) {
      return it->second;
    } else {
      // key not found, do something about it
    }
  }
于 2013-09-06T07:09:06.553 に答える
0

juanchopanza さんからすばらしい回答がありました

boost無効なものを返す方法を示したかっただけです

空の型を返すことがboost::optionalできます

#include<boost\optional.hpp>
...

boost::optional<int> GetValue(int key){

    auto it = testMap.find(key);
    if (it != testMap.end()) {
      return it->second;
    } else {
      return boost::optional<int>();
    }
}


boost::optional<int> val = GetValue(your_key);
if(!val) //Not empty
{

}
于 2013-09-06T07:26:24.580 に答える