How to find const int * in std :: set <int *>?
Firstly, I have a set
std::set<int*> my_set; Then I have a function to check if a specific pointer int p exists in my_set , which does nothing but return true if it has a pointer, and false otherwise.
Since the function does not change the reference int , it is natural to take a pointer as const int* , i.e.
bool exists_in_my_set(const int* p) { return my_set.find(p) != my_set.end(); } However, when I try to compile the code, I get the following error:
error: invalid conversion from 'const int*' to 'std::set<int*>::key_type {aka int*}' [-fpermissive] In other words, the compiler tries to pass const int* to int* when I call find .
Anyway, my question is: how can I find p in my_set or at least figure out if p exists in my_set or not using the existing definitions of p and my_set
You can declare a set as follows
std::set<const int*> my_set; ... if you do not need to change int , getting its pointer from the set. This can happen if the lifetime * and ints in the set are managed elsewhere, and the set is just a validation method if you already know about the specific existence of the int / object.
(* although you can really remove const int* .)
You can use const_cast<> to remove the constant from the parameter before searching for set<> :
return my_set.find(const_cast<int*>(p)) != my_set.end(); There is no technical reason why the library cannot support what you expect, but on the other hand, the forced explicit const_cast documents that the operation with the const pointer somehow gets non- const access through set ... maybe a good documentation, that- then a little unusual.