7

首先,我有一套

std::set<int*> my_set;

然后,我有一个函数用于检查特定的 int 指针是否p存在于 中,它只my_set返回true指针是否存在于其中,false否则返回。

由于函数不会修改被引用的int,所以很自然的将指针当做 a const int*,即

bool exists_in_my_set(const int* p)
{
    return my_set.find(p) != my_set.end();
}

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

error: invalid conversion from 'const int*' to 'std::set<int*>::key_type {aka int*}' [-fpermissive]

换句话说,const int*int*我调用find.

无论如何,我的问题是:我怎样才能找到pmy_set或者至少找出是否p存在于my_set,使用现有的定义pmy_set

4

2 回答 2

5

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

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

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

于 2013-11-11T10:09:20.243 回答
1

您可以像这样声明集合

std::set<const int*> my_set;

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

(* 虽然你实际上可以删除一个const int*.)

于 2013-11-11T10:59:44.613 回答