gpt4 book ai didi

c++ - 如何通过传递命名函数为 unordered_set 显式指定自定义哈希函数?

转载 作者:太空狗 更新时间:2023-10-29 20:12:21 26 4
gpt4 key购买 nike

基于对 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com