加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:56:11 所属栏目:百科 来源:网络整理
导读:基于对 this question的接受答案,可以使用std的特化来为用户定义的类型提供散列函数. #include unordered_set#include stdint.hstruct FooBar { int i; };namespace std { template struct hashFooBar { size_t operator()(const FooBar x) const { return x
基于对 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);
}

什么是正确的模板魔术和方法签名才能使其工作?

解决方法

你需要提供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);
}

我还应该注意,提供“仿函数”而不是函数更受欢迎,因为前者可以内联,而后者可能不会内联.

#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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读