c++ - 如何将 unordered_set 与比较函数一起使用?

标签 c++ c++11 std unordered-set

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

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

在 Node 类中。现在我尝试在我的无序集中使用这个函数,

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

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

最佳答案

编译器是对的。没有构造函数允许您仅传递 KeyEqual 作为参数。您需要使用另一个构造函数(请参阅 here )或更改函数的类型。

例如您可以使用一个辅助结构来包装 HasSamePosition 调用并覆盖 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();
}

关于c++ - 如何将 unordered_set 与比较函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36058387/

相关文章:

c++ - 如何在调整大小的 std::vector 的最后一个元素之后插入?

c++ - 从 std::stringstream 中提取位到 std::bitset

c++ - 为什么右值不能绑定(bind)左值引用?

c++ - Pig Latin、for循环、字符串问题

c++ - 每个 memory_order 是什么意思?

c++ - 从 lambda 获取捕获的变量?

c++ - 互斥锁的顺序

android - cstdlib 的 NDK 错误

c++ - BST 插入 C++ 帮助

c++ - 错误 1 ​​错误 C2678 : binary '!=' : no operator found which takes a left-hand operand of type 'std::ofstream' (or there is no acceptable conversion)