如何在比较功能中使用unordered_set? [英] How to use unordered_set with compare function?

查看:102
本文介绍了如何在比较功能中使用unordered_set?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为std :: unorderd_set的第三个模板参数编写了自己的比较函数。
我的功能是

I wrote my own compare function for the third template parameter of std::unorderd_set. My function is

static bool HasSamePosition(const Node& a, const Node& b);

。现在,我尝试在我的无序集中使用此功能,

in the class Node. Now I'm trying to use this function in my unordered set,

std::unordered_set<Node, std::hash<Node>, bool(*)(const Node& a, const Node& b)> closedlist(&Node::HasSamePosition);

,但是它不起作用。错误是,没有构造函数的实例与参数列表匹配。我缺少什么?

but it doesn't work. The error ist, that no instance of the constructor is matching the argumentlist. What am I missing?

推荐答案

编译器正确。没有构造函数只允许您传递 KeyEqual 作为参数。您需要使用其他构造函数(请参见此处)或更改您的功能。

Well the compiler is right. There is no constructor that allows you to only pass KeyEqual as parameter. You need to use another constructor (see here) or change the type of your function.

例如您可以使用包装在HasSamePosition调用周围的辅助结构,并覆盖 operator()(const Node& a,const Node& b)

E.g. You could use a helper struct that wraps around your HasSamePosition call and override operator()(const Node& a, const Node& b)

struct Node{
    static bool HasSamePosition(const Node& a, const Node& b);
};

struct NodeEqual
{
    bool operator()(const Node& a, const Node& b) { return Node::HasSamePosition(a, b); }
};

int main()
{
    std::unordered_set<Node, std::hash<Node>, NodeEqual> closedlist();
}

这篇关于如何在比较功能中使用unordered_set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆