C++ 函数参数前的const关键字是否也会阻止从中读取数据?
据我所知,函数参数前的C++ 函数参数前的const关键字是否也会阻止从中读取数据?,c++,visual-studio,stdmap,C++,Visual Studio,Stdmap,据我所知,函数参数前的const关键字承诺不会修改传入的数据(如果它是通过ref传递的),但在这种情况下,它似乎也会阻止数据的读取。为什么会这样 我试图把一些字符串映射成一些整数。还有一些函数将map(按const-ref)和字符串(按const-ref)作为参数。但是,当我尝试这样做时,这不知何故不起作用:int val=my_map[str] 但是,当我从参数中的映射之前删除const关键字时,效果很好。但我不想复制整个地图。为什么警察在这个案子里表现得很奇怪 //当然,这不是实际的代码。但
const
关键字承诺不会修改传入的数据(如果它是通过ref传递的),但在这种情况下,它似乎也会阻止数据的读取。为什么会这样
我试图把一些字符串映射成一些整数。还有一些函数将map(按const-ref)和字符串(按const-ref)作为参数。但是,当我尝试这样做时,这不知何故不起作用:int val=my_map[str]代码>
但是,当我从参数中的映射之前删除const关键字时,效果很好。但我不想复制整个地图。为什么警察在这个案子里表现得很奇怪
//当然,这不是实际的代码。但这一错误是重复的
int get_val(const std::map<std::string, int>& map, const std::string& s) {
return map[s]; // This doesn't compile
}
int main() {
std::map <std::string, int> map;
map["foo"] = 21;
std::cout << get_val(map, "foo");
}
我已经链接了特定于您的问题的重复项,即为什么您不能在const std::map&
上使用operator[]
。为了获得更全面的理解,您应该了解const
-限定方法的用途,例如,via。总是使用std::map::operator[]
很有诱惑力,但无论是插入和元素还是访问一个,在这两种情况下operator[]
都比您实际想要的做得更多,最好使用insert
或find
在地图中插入/查找元素,并且operator[]
仅当您希望“如果键不存在并访问,则默认构造值”
Severity Code Description Project File Line Suppression State
Error C2678 binary '[': no operator found which takes a left-hand operand of type 'const std::map<std::string,int,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' (or there is no acceptable conversion)
with
[
_Kty=std::string,
_Ty=int
] Delete C:\Users\abusa\source\repos\Delete\Delete\Source.cpp 6