我有一个结构体作为std::unordered_map的键。我已经编写了自定义哈希函数和比较谓词。当我尝试编译代码时,出现以下错误-
以下是代码段-
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)
必须为const// 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中:关于c++ - 带有自定义哈希函数和比较谓词的unordered_map提供编译错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63417810/