c++ - 带有自定义散列函数和比较谓词的 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;
}
解决方案
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
,最多在比较器的命名要求中:
[...] 该表达式的评估不允许通过取消引用的迭代器调用非常量函数。
推荐阅读
- javascript - 从内部返回函数返回时,管道不是函数
- javascript - 如何用由数组组成的 ul 列表替换 DOM 元素?
- karate - 在空手道中执行断言时出现错误“实际值不是字符串”
- c++ - 字符数组地址和整数数组地址
- java - Spring Security 中的 authorizeRequests 有什么作用?
- javascript - setstate - 动态键值 - 覆盖不合并状态
- angular - 无法读取未定义 Angular 7 的属性“订阅”
- java - 请求的配置文件“pom.xml”无法激活,因为它不存在
- c# - 处理多个具有超时的 CancellationToken
- elasticsearch - SQL 类似于 GROUP BY AND HAVING 示例