Search code examples
c++c++11stdunordered-set

How to use unordered_set with compare function?


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?


Solution

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