如何通过传递命名函数为unordered_set显式指定自定义哈希函数? [英] How do I specify a custom hash function explicitly for unordered_set by passing a named function?

查看:72
本文介绍了如何通过传递命名函数为unordered_set显式指定自定义哈希函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于对此问题的答案,则可以使用特殊化来 std 为用户定义的类型提供哈希函数.

Based on the accepted answer to this question, one can use a specialization to std to provide a hash function for a user defined type.

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

但是,文档似乎暗示自定义哈希函数也可以是显式传递给构造函数,并且我想为此哈希函数使用命名函数.

However, the documentation seems to imply that a custom hash function can also be passed explicitly into the constructor, and I would like to use a named function for this hash function.

但是,我目前的尝试遇到了编译错误.

However, my current attempt suffers from compile errors.

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

完成这项工作的正确模板魔术和方法签名是什么?

What is the correct template magic and method signature to make this work?

推荐答案

您需要提供哈希器的类型,在您的情况下,该类型是函数指针.并且您的 FooBar 类型必须具有相等的可比性.或者等效地,您可以提供与提供哈希器相同的方式提供相等谓词.

You need to supply the type of the hasher, which is in your case a function pointer. And your FooBar type must be equality comparable. Or equivalently you could supply a equality predicate in the same manner as supplying the 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);
}

我还应该指出,提供函数器"而不是函数是比较流行的,因为前者可以内联,而后者可能不内联.

I should also note that it is more popular to supply a "functor" instead of a function, as the former can be inlined, while the latter is likely to not be inlined.

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

这篇关于如何通过传递命名函数为unordered_set显式指定自定义哈希函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆