首页 > 解决方案 > 带有自定义散列函数和比较谓词的 unordered_map 会产生编译错误

问题描述

我有一个结构作为 std::unordered_map 的键。我已经编写了自定义哈希函数和比较谓词。当我尝试编译代码时,出现以下错误-

错误:静态断言失败:键相等谓词必须可以用键类型 1831 的两个参数调用 | static_assert(__is_invocable<const _Equal&, const _Key&, const _Key&>{},

以下是代码片段-

using namespace std;
struct keys
{
    int port_num;
};

struct fields
{
    int priority;
};

struct container_hash {
    std::size_t operator()(struct keys const& c) const {
        return hash<int>{}(c.port_num);
    }
};

struct container_equal {
    bool operator()(struct keys const& k1, struct keys const& k2)
    {
        return k1.port_num == k2.port_num;
    }
};

int main()
{
    unordered_map<struct keys, struct fields, container_hash, container_equal> hashmap;
    struct keys k;
    k.port_num = 8;
    struct fields f;
    f.priority = 2;
    hashmap[k] = f;
}

标签: c++hashmapunordered-map

解决方案


bool operator()(struct keys const& k1, struct keys const& k2)

必须是常量

//                                                            VVVVV
bool operator()(struct keys const& k1, struct keys const& k2) const

您还可以在错误消息中看到该函数必须可在对象的 const 引用上调用

//                           VVVVV       V
static_assert(__is_invocable<const _Equal&, const _Key&, const _Key&>{},

我在标准中找不到任何明确表示,它必须是const,最多在比较器的命名要求中

[...] 该表达式的评估不允许通过取消引用的迭代器调用非常量函数。


推荐阅读