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.
A key in a map is semantically immutable, all map operations that allow direct access to keys do that by const
-qualifying the key type (e.g. value_type
is defined as pair<const Key, T>
).
In case of int*
key type however you'd get a const
pointer to non-const int
(int*const
), which isn't very nice (it still works, since only the pointer value is used as the key, but the semantics of immutability become diluted, which can lead to bugs).
Instead of casting away constness, just change the map
to map<const int*, double>
.
Then it will work for const int*
as well as int*
keys.
#include <map>
std::map<const int*, double> mymap;
double myfind(const int * mykey)
{
return mymap.find(mykey)->second; // just works
}
double myfind(int * mykey)
{
return mymap.find(mykey)->second; // also works
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With