You may have a const-correctness issue. const int *
may not be what you think it is. It is a pointer to a constant integer. This is not the same as the key type of your map, which is a pointer to a (non-constant) integer. And neither are the same as int * const
which is a constant pointer to a (non-constant) integer. The issue isn't whether the key value itself is mutable or immutable, it's whether the things you're storing pointers to are mutable or immutable.
For example, this compiles:
std::map<int *, double> mymap;
double myfind(int * const mykey) {
return mymap.find(mykey)->second;
}
As does this:
std::map<const int *, double> mymap;
double myfind(const int *mykey) {
return mymap.find(mykey)->second;
}
double myfind2(const int * const mykey) {
return mymap.find(mykey)->second;
}
Do you see the difference? In your original code, the compiler is quite right to flag an error. If your function takes a const int *
, then you are in effect promising not to modify the int
pointed to by the pointer I pass in. But if you use such a pointer as int *
in the key of a std::map
, you may be allowing someone to modify that int
.
In this particular case, we know that std::map::find()
will not assign to a pointer argument, but the compiler doesn't, which is why const_cast<>
exists as pointed out in other answers.
const_cast
– Skinstd::less<int *>
andstd::less<const int *>
– Kipkipling