unordered_map 使用自定义哈希函数和比较谓词给出编译错误
unordered_map with custom hash function and comparison predicate gives compilation error
我有一个结构作为 std::unordered_map 的键。我已经编写了自定义哈希函数和比较谓词。当我尝试编译代码时出现以下错误-
error: static assertion failed: key equality predicate must be invocable with two arguments of key type
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
,最多在named requirement for comparators:
[...] evaluation of that expression is not allowed to call non-const functions through the dereferenced iterators.
我有一个结构作为 std::unordered_map 的键。我已经编写了自定义哈希函数和比较谓词。当我尝试编译代码时出现以下错误-
error: static assertion failed: key equality predicate must be invocable with two arguments of key type 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
,最多在named requirement for comparators:
[...] evaluation of that expression is not allowed to call non-const functions through the dereferenced iterators.