【发布时间】:2016-11-02 08:29:08
【问题描述】:
我有一个指针类型的set,但使用 const 指针搜索是不可能的,我的代码如下:
#include <set>
#include <string>
using namespace std;
struct Node
{
string name;
int id;
Node(const string &name, int id):
name(name),
id(id)
{}
};
struct Comprator
{
bool operator()(const Node* lhs, const Node* rhs) const
{
return lhs->id < rhs->id;
}
};
int
main(int argc, char *argv[])
{
set<Node*, Comprator> d;
Node* node3 = new Node("foo", 4);
d.insert(node3);
const Node* node4 = node3;
auto it = d.find(node4);
return 0;
}
我收到以下错误:
main.cc: In function ‘int main(int, char**)’:
main.cc:38:25: error: invalid conversion from ‘const Node*’ to ‘std::set<Node*, Comprator>::key_type {aka Node*}’ [-fpermissive]
auto it = d.find(node4);
^
In file included from /usr/include/c++/5/set:61:0,
from main.cc:2:
/usr/include/c++/5/bits/stl_set.h:694:7: note: initializing argument 1 of ‘std::set<_Key, _Compare, _Alloc>::iterator std::set<_Key, _Compare, _Alloc>::find(const key_type&) [with _Key = Node*; _Compare = Comprator; _Alloc = std::allocator<Node*>; std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator<Node*>; std::set<_Key, _Compare, _Alloc>::key_type = Node*]’
find(const key_type& __x)
如果我将 Node* 更改为 int 一切正常,我不明白问题所在。我使用 c++11 和 g++-5.4.0。
编辑:
正如@Piotr Skotnicki 在 c++14 的 cmets 中解释的那样,下面的比较器代码可以编译:
struct Comprator
{
using is_transparent = void;
bool operator()(const Node* lhs, const Node* rhs) const
{
return lhs->id < rhs->id;
}
};
【问题讨论】:
-
您可以在
Comprator的声明中添加using is_transparent = void; -
我将语句添加到我的比较器类中,但没有任何改变。
-
您需要使用
-std=c++14模式标志 -
是的,它有效,感谢您的帮助。如果有的话,请给我一个链接,以找出这在 c++14 中有效的原因。