根据对此问题的接受答案,可以使用专门化为std用户定义的类型提供哈希函数.
#include <unordered_set>
#include <stdint.h>
struct FooBar {
int i;
};
namespace std {
template <> struct hash<FooBar>
{
size_t operator()(const FooBar & x) const
{
return x.i;
}
};
}
int main(){
std::unordered_set<FooBar> foo(0);
}
Run Code Online (Sandbox Code Playgroud)
但是,文档似乎暗示自定义散列函数也可以显式传递给构造函数,我想为这个散列函数使用一个命名函数.
但是,我当前的尝试遭受编译错误.
#include <unordered_set>
#include <stdint.h>
struct FooBar {
int i;
};
const size_t hashFooBar(const FooBar& foo) {
return foo.i;
}
int main(){
std::unordered_set<FooBar> foo(0, hashFooBar);
}
Run Code Online (Sandbox Code Playgroud)
什么是正确的模板魔术和方法签名才能使其工作?
你需要提供hasher的类型,在你的情况下是一个函数指针.你的FooBar类型必须是相等的.或者等效地,您可以以与提供hasher相同的方式提供等式谓词.
#include <unordered_set>
#include <stdint.h>
struct FooBar {
int i;
};
bool operator==(const FooBar& x, const FooBar& y)
{
return x.i == y.i;
}
size_t hashFooBar(const FooBar& foo) {
return foo.i;
}
int main(){
std::unordered_set<FooBar, size_t(*)(const FooBar&)> foo(0, hashFooBar);
}
Run Code Online (Sandbox Code Playgroud)
我还应该注意,提供"仿函数"而不是函数更受欢迎,因为前者可以内联,而后者可能不会内联.
#include <unordered_set>
#include <stdint.h>
struct FooBar {
int i;
};
bool operator==(const FooBar& x, const FooBar& y)
{
return x.i == y.i;
}
struct hashFooBar
{
size_t operator()(const FooBar& foo) const {
return foo.i;
}
};
int main(){
std::unordered_set<FooBar, hashFooBar> foo(0);
}
Run Code Online (Sandbox Code Playgroud)