C++:在指针集中查找

标签 c++ pointers stl constants

下面的例子说明了我的问题:

#include <set>

class A {};

int main()
{
    A a;
    A * p = &a;
    const A * cp = &a;

    std::set<A*> s;
    s.insert(p);
    s.find(cp);
}

编译结束于:

a.cpp: In function ‘int main()’:
a.cpp:13:18: error: invalid conversion from ‘const A*’ to ‘std::set<A*>::key_type {aka A*}’ [-fpermissive]
         s.find(cp);
                  ^
In file included from /usr/include/c++/4.9.1/set:61:0,
                 from a.cpp:1:
/usr/include/c++/4.9.1/bits/stl_set.h:701:7: note: initializing argument 1 of ‘std::set<_Key, _Compare, _Alloc>::iterator std::set<_Key, _Compare, _Alloc>::find(const key_type&) [with _Key = A*; _Compare = std::less<A*>; _Alloc = std::allocator<A*>; std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator<A*>; std::set<_Key, _Compare, _Alloc>::key_type = A*]’
       find(const key_type& __x)

我知道为什么它不能编译,但是有没有比 s.find((A*)cp) 更丑陋和更残酷的解决方案? set 和 const 指针都给出了。

最佳答案

一个选项是使用 C++14 transparent operator functors连同 heterogeneous lookup :

std::set<A*, std::less<>> s;
s.find(cp);

不幸的是,libstdc++ 目前不支持异构查找,但是 it's marked as WIP . (它在 clang/libc++ 和下一版本的 Visual Studio 中的 will be available 中可用。)没有它,您几乎只能使用 const_casting cp

关于C++:在指针集中查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25878437/

相关文章:

C++在访问持有该成员的对象时无法访问对象成员

c++ - 一个变量的一行 extern "C"- 合法吗?

c++ - 调用派生类型的模板化函数

c++ - boost::optional 到 bool 的转换

c++ - 从原始指针到 boost::shared_ptr 的转换:使用 share_from_this 的树实现

c++ - 如何在 C++ 中定义 vector 的 vector ?

c++ - vec.erase(vec.end());合法的?

c++ - 这个 boost::tuple 代码可以转换为纯 std::standard 库代码吗?

c++ - 我应该从使用 boost::shared_ptr 切换到 std::shared_ptr 吗?

c++ - C++ 中的按位与