C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 如何通过传递命名函数为unordered_set显式指定自定义哈希函数?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_197_4@ 基于对 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);
}

大佬总结

以上是大佬教程为你收集整理的c – 如何通过传递命名函数为unordered_set显式指定自定义哈希函数?全部内容,希望文章能够帮你解决c – 如何通过传递命名函数为unordered_set显式指定自定义哈希函数?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。