Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find by a const pointer key in a map with non-const pointer keys

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.

like image 383
bedrorom Avatar asked Feb 08 '19 08:02

bedrorom


1 Answers

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
}
like image 105
rustyx Avatar answered Oct 06 '22 19:10

rustyx