【问题标题】:unordered_map with custom hash function and comparison predicate gives compilation error具有自定义散列函数和比较谓词的 unordered_map 会产生编译错误
【发布时间】:2020-12-04 15:20:39
【问题描述】:

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

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

下面是代码sn-p-

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++ 中,在使用 struct 之前不需要 struct。例如struct keys k; 应该只是keys k;

标签: c++ hashmap unordered-map


【解决方案1】:
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,最多在named requirement for comparators

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

【讨论】:

    猜你喜欢
    • 2012-02-11
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    相关资源
    最近更新 更多