Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 872
HelloGoodbye Avatar asked Nov 11 '13 10:11

HelloGoodbye


People also ask

What is const int * A?

int *const is a constant pointer to integer This means that the variable being declared is a constant pointer pointing to an integer. Effectively, this implies that the pointer shouldn't point to some other address.

What is the difference between int * const C and const int * C?

const int * And int const * are the same. const int * const And int const * const are the same. If you ever face confusion in reading such symbols, remember the Spiral rule: Start from the name of the variable and move clockwise to the next pointer or type.

What is const int function?

int const function(parameters) The const is redundant. Declaring a simple type such as int as a const return value is not useful, although it may help to make the code more self-documenting. If the return type is a reference or pointer however then the story changes.

How do you declare a constant pointer in C++?

Pointers with a constant memory address are declared by including the const after the *. Because the address is const, the pointer must be assigned a value immediately.


1 Answers

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.

like image 78
Tony Delroy Avatar answered Sep 24 '22 02:09

Tony Delroy