下面的例子说明了我的问题:
#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_cast
ing cp
。
关于C++:在指针集中查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25878437/