The following C++ code does not compile because it's passing a non-const pointer to a find() function which expects a const pointer.
#include <map>
std::map<int*, double> mymap;
double myfind(const int * mykey)
{
return mymap.find(mykey)->second;
}
Is there a way how to make the finding work without changing the type of the map or making variable mykey non-const?
After all the function find() does not modify the pointed object, it just compares the pointers.
I think I have found a solution, but it requires C++14 transparent comparators.
An excellent article about C++14 transparent comparators can be found here. To be completely honest, by adding the comparator, the type of
mymapslightly changed which I originally didn't want to, but it's the best solution I could find.If C++14 is not available, there are at least two evils we can choose from. The first one is to copy
mymapto a newstd::map<const int*, double>inmyfind, which is horribly unefficient. The second one is casting away constness by using aconst_cast<int*>(mykey)which should be avoided if possible.