From what I know, the const
keyword before a function parameter promises that the will not modify the data passed in (if it's passed by ref.) But in this case it seems to me that it blocks the reading of data too. Why is it happening?
I was trying to map some strings to some integers. And there was some function that took the map (by const ref.) and a string (by const ref) as argument. But this somehow doesn't work when I try to do things like: int val = my_map[str];
But when I remove the const keyword from before the map in the parameter, this works just fine. But I don't want to copy the whole map. Why the const is acting weird in this case?
// Of course this is not the actual code. But the error is reproduced.
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");
}
I expected the output to be 21
. But I get this error:
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