作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
基于对 this question 的公认答案,可以使用 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);
}
然而,documentation似乎暗示自定义哈希函数也可以显式传递给构造函数,我想为这个哈希函数使用命名函数。
但是,我目前的尝试遇到了编译错误。
#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);
}
使这项工作有效的正确模板魔法和方法签名是什么?
最佳答案
您需要提供散列器的类型,在您的情况下是函数指针。并且您的 FooBar
类型必须是可比较的。或者等效地,您可以使用与提供散列器相同的方式提供相等谓词。
#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);
}
我还应该指出,提供“仿函数”而不是函数更受欢迎,因为前者可以内联,而后者可能不会内联。
#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);
}
关于c++ - 如何通过传递命名函数为 unordered_set 显式指定自定义哈希函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28120908/
我是一名优秀的程序员,十分优秀!