[英]How can I find a const int* in an std::set<int*>?
首先,我有一套
std::set<int*> my_set;
然后,我有一个函数来检查my_set
是否存在特定的int指针p
, my_set
指针存在于其中my_set
返回true
否则返回false
。
由于函数不修改引用的int
,因此将指针作为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]
换句话说,当我调用find
时,编译器会尝试将const int*
转换为int*
。
不管怎样,我的问题是: 我如何才能找到p
在my_set
,或至少找出是否p
中存在my_set
与否,使用的现有定义p
和my_set
?
在搜索set<>
之前,您可以使用const_cast<>
从参数中删除const_cast<>
:
return my_set.find(const_cast<int*>(p)) != my_set.end();
没有特别的技术原因,库不支持允许你期望的,但另一方面 - 强制显式const_cast
记录涉及const
指针的操作以某种方式通过set
获得非const
访问...可以说是好的记录有点不寻常的事情。
您可以像这样声明集合
std::set<const int*> my_set;
... 如果你永远不需要通过从集合中获取指针来修改int
。 如果集合中的int的生命周期*和值在其他地方进行管理,并且该集合只是一种检查您是否已经知道特定int / object存在的方法,则可能就是这种情况。
(*虽然你实际上可以删除一个const int*
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.