How to use unordered_set with compare function?

 ̄綄美尐妖づ 提交于 2019-12-11 12:48:06

问题


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?


回答1:


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();
}



回答2:


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;


来源:https://stackoverflow.com/questions/36058387/how-to-use-unordered-set-with-compare-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!