HelloGoodbye
HelloGoodbye

Reputation: 3902

How can I find a const int* in an std::set<int*>?

First, I have a set

std::set<int*> my_set;

Then, I have a function for checking whether a specific int pointer p exists in my_set, that does nothing more than returning true if it the pointer exists in it, and false otherwise.

Since the function does not modify the referenced int, it is natural to take the pointer as a const int*, that is

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 cast the const int* to an int* when I call find.

Anyway, my question is: How can I find p in my_set, or at least find out whether p exists in my_set or not, using the existing definitions of p and my_set?

Upvotes: 7

Views: 1001

Answers (2)

Grimm The Opiner
Grimm The Opiner

Reputation: 1806

You can declare the set like this

std::set<const int*> my_set;

...if you never need to modify an int by getting it's pointer from the set. This might be the case if the lifetime* and values of the ints in the set are managed elsewhere and the set is just a method of checking if you're already aware of a particular int/object's existence.

(* although you can actually delete a const int*.)

Upvotes: 1

Tony Delroy
Tony Delroy

Reputation: 106086

You can use const_cast<> to remove constness from the parameter before searching the set<>:

return my_set.find(const_cast<int*>(p)) != my_set.end();

There's no particular technical reason the library couldn't support allow what you expect, but on the other hand - forcing an explicit const_cast is documenting that an operation involving a const pointer is somehow getting non-const access through the set... arguably nice documentation that something a little unusual is up.

Upvotes: 5

Related Questions