【发布时间】:2014-11-10 18:33:57
【问题描述】:
下面的例子说明了我的问题:
#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 指针都给出了。
【问题讨论】:
-
将集合的类型更改为
set<const A*>是一个选项吗? -
but is there any solution less ugly and brutal没有指针集。 -
const A *与A *不同! -
@PaulMcKenzie 一组智能指针再好不过了。
-
在
find中,您正在搜索const元素,但是该集合被声明为具有非常量元素。
标签: c++ pointers stl constants