How to use unordered_set with compare function?

2019-08-14 15:27发布

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?

2条回答
成全新的幸福
2楼-- · 2019-08-14 15:35

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.

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();
}
查看更多
唯我独甜
3楼-- · 2019-08-14 15:42

It's easier to use a class:

class Node
{ 
    public:
        class HasSamePosition
        {
            bool operator()(const Node& a, const Node& b)
            { 
                // Put here content of your HasSamePosition function
            }
        };
    ....
};

std::unordered_set<Node, std::hash<Node>, Node::HasSamePosition> closedlist;
查看更多
登录 后发表回答