Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将运算符[]与常量方法中的映射一起使用_C++ - Fatal编程技术网

C++ 将运算符[]与常量方法中的映射一起使用

C++ 将运算符[]与常量方法中的映射一起使用,c++,C++,假设我有一个这样的方法 int someclass::somemethod(const std::string &name) const { std::string a = mymap["a"]; ..... } 我的地图在哪里 std::map<std::string,std::string> std::map 这就是我得到的错误 Error 1 error C2678: binary '[' : no operator fou

假设我有一个这样的方法

int someclass::somemethod(const std::string &name) const
{
       std::string a = mymap["a"];
       ..... 
}
我的地图在哪里

std::map<std::string,std::string> 
std::map
这就是我得到的错误

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)    
Error 1 Error C2678:二进制“[”:未找到接受“const std::map”类型左侧操作数的运算符(或没有可接受的转换)

关于如何访问键值的任何建议???

使用map的
。查找
成员函数进行搜索

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

if (it != mymap.end())
    // it->first = key, it->second = mapped value.

使用
operator[]
而不是
find
不会使搜索工作得更好。要么键匹配(在这种情况下
find
将正常工作),要么键不匹配(在这种情况下
[]
尝试使用该键插入一个新节点,该键将与一个值初始化值(本例中为空字符串)关联

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


是的,可以使用
const
容器定义
操作符[]
,例如在请求的键不存在时/如果请求的键不存在时抛出异常,但是现在还不能定义为这样,而且可能不会很快出现。

std::map::operator[]
有一个(邪恶(!?)非常量副作用。如果该元素不存在,则运算符会添加一个新元素。
somemethod()
声明为
const
,因此
std::map
也是
const
且无法修改。因此,非常量
运算符[]
不能应用于
const std::map
。可选方法有
std::map::find()
std::map::at()
(C++11).

使用map::find获取元素的迭代器。编写一个包含映射示例声明和映射访问的函数是一种很好的形式。我知道我可以这样做,但是由于一些疯狂的原因,映射返回end(),并且我确定该项在容器中。这就是为什么我想使用[]运算符Using
运算符[]
执行搜索没有帮助。名称匹配(在这种情况下,
查找
可以正常工作)或者不匹配(在这种情况下,
[]
将插入一个新节点,该节点具有新键和一个值初始化映射值——在这种情况下为空字符串)@MistyD我对这个问题并不完全熟悉,而且这个问题可能在没有SSCCE的情况下就可以被识别出来,但是在很多情况下,用户会问一些关于分段代码块的问题(就像你一样)真正的问题存在于提供的代码之外。为了便于将来参考,通常最好在问题如此容易重现的情况下创建一个。
std::map::at()
也可能是一个不错的选择。@juanchopanza:是的,但只适用于C++11及更高版本。无论如何,
find()
返回一个interator,可以很容易地检查元素是否存在。但是
at()
如果元素不存在,就会抛出一个
std::out\u范围。@RemyLebeau这比当前标准早一个。我们在2015年;-)@ JuangopaZaS:是的,但是MaultC++编译器还不支持C++ 11,或者只支持它的一部分。@ ReMyLeBeAube,这可能是答案中的一个可选注释。问题不指定C++ 03,所以我看不到任何理由限制对旧标准的答案。