如何在std :: set <int*>中找到const int*?

Hel*_*bye 6 c++ templates pointers const find

首先,我有一套

std::set<int*> my_set;
Run Code Online (Sandbox Code Playgroud)

然后,我有一个函数来检查一个特定的int指针是否p存在my_set,只有true当指针存在于其中时才会返回,false否则.

由于引用的函数不会修改int,很自然地把指针作为const int*,那就是

bool exists_in_my_set(const int* p)
{
    return my_set.find(p) != my_set.end();
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试编译代码时,我收到以下错误:

error: invalid conversion from 'const int*' to 'std::set<int*>::key_type {aka int*}' [-fpermissive]
Run Code Online (Sandbox Code Playgroud)

换句话说,编译器会在我调用时尝试将其const int*转换为.int*find

不管怎样,我的问题是:我如何才能找到p的my_set,或至少找出是否p存在my_set与否,使用的现有定义p和my_set?

Ton*_*roy 5

您可以const_cast<>在搜索之前使用从参数中删除常量set<>:

return my_set.find(const_cast<int*>(p)) != my_set.end();
Run Code Online (Sandbox Code Playgroud)

没有特别的技术原因库不能支持你所期望的,但另一方面 - 强制显式const_cast是记录涉及const指针的操作以某种方式const无法通过set......可以说是很好的文档小不寻常就是了。


Gri*_*ner 1

你可以这样声明集合

std::set<const int*> my_set;
Run Code Online (Sandbox Code Playgroud)

...如果您永远不需要int通过从集合中获取它的指针来修改它。如果集合中 int 的生命周期*和值在其他地方进行管理,并且集合只是检查您是否已经知道特定 int/对象存在的方法,则可能会出现这种情况。

(* 尽管您实际上可以删除const int*.)