在const方法中使用operator []和map

Mis*_*tyD 0 c++

说我有这样的方法

int someclass::somemethod(const std::string &name) const
{
       std::string a = mymap["a"];
       ..... 
}
Run Code Online (Sandbox Code Playgroud)

mymap的位置

std::map<std::string,std::string> 
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

Error   1   error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<std::string, std::string>   ' (or there is no acceptable conversion)    
Run Code Online (Sandbox Code Playgroud)

关于如何获取密钥值的任何建议??

Jer*_*fin 6

使用map的.find成员函数进行搜索.

auto it = mymap.find("a");

if (it != mymap.end())
    // it->first = key, it->second = mapped value.
Run Code Online (Sandbox Code Playgroud)

使用operator[]而不是find不会使搜索工作更好.密钥匹配(在这种情况下find可以正常工作)或者它们不匹配(在这种情况下[]尝试插入具有该密钥的新节点,该节点将与值初始化值相关联 - 此处为空字符串案件.

这是后一种行为(插入新节点),这意味着没有const版本operator[].

是的,可以以operator[]一种与const容器一起工作的方式定义,例如在/如果所请求的密钥不存在时抛出异常 - 但它现在没有被定义为以这种方式工作,并且可能不会也许很快.


小智 5

std::map::operator[]有一个(恶(!?))非恒定的副作用.如果该元素尚不存在,则运算符将添加新元素.somemethod()声明为const,所以std::map也是const,也不能修改.因此,非常数operator[]不能应用于const std::map.替代品是std::map::find()std::map::at()(C++ 11).