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

时间:2013-11-11 10:03:11

标签: c++ templates pointers find const

首先,我有一套

std::set<int*> my_set;

然后,我有一个函数来检查p中是否存在特定的int指针my_set,如果指针存在于其中,则只返回true,{ {1}}否则。

由于该函数不修改引用的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] 时,编译器会尝试将const int*强制转换为int*

无论如何,我的问题是:如何在find中找到p,或至少知道my_set中是否存在pmy_setp的现有定义?

2 个答案:

答案 0 :(得分:4)

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

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

没有特别的技术原因,库不支持允许你所期望的,但另一方面 - 强制显式const_cast正在记录涉及const指针的操作以某种方式变为非 - const访问set ...可以说很好的文档,有点不寻常的事情。

答案 1 :(得分:1)

您可以像这样声明集合

std::set<const int*> my_set;

... 如果,您永远不需要通过从集合中获取指针来修改int。如果集合中的int的生命周期*和值在其他地方进行管理,那么可能就是这种情况,而set只是一种检查你是否已经知道特定int / object存在的方法。

(*虽然您实际上可以删除const int*。)

相关问题