如何解决带有自定义哈希函数和比较谓词的unordered_map提供编译错误
我有一个结构体作为std :: unordered_map的键。我已经编写了自定义哈希函数和比较谓词。当我尝试编译代码时,出现以下错误-
错误:静态断言失败:键相等性谓词必须可使用键类型的两个参数来调用 1831 | static_assert(__ is_invocable
{},
以下是代码段-
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
,最多只能是named requirement for comparators:
[...]对该表达式的求值不允许通过取消引用的迭代器来调用非const函数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。