基于const指针在std :: set中查找指针

时间:2017-11-05 14:10:40

标签: c++ pointers set const

以下代码因标记的行无法使用,因为s.find需要int*,而不是const int*。由于变量b没有任何变化,为什么不能这样调用方法?有没有比const_cast更好的方式?

#include <set>

int main()
{
    int x = 5;
    int* a = &x;
    const int* b = a;

    std::set<int*> s;
    s.insert(a);
    s.find(b); // does not work
    s.find(const_cast<int*>(b)); // does work, but const_cast
}

错误是

  

error: no matching function for call to 'std::set<int*>::find(const int*&)'

之后它尝试隐式转换,并以

失败
  

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

0 个答案:

没有答案