繁体   English   中英

c++:如何通过正常的 c function 作为 Z0800FC577294C34E0B28AD2839 仿函数Z0800FC577294C34E0B28AD2839

[英]c++ : How to pass a normal c function as hash functor for unordered_map

我有这个 hash function 是 C 风格:

static size_t Wang_Jenkins_hash(size_t h) {
    h += (h << 15) ^ 0xffffcd7d;
    h ^= (h >> 10);
    h += (h << 3);
    h ^= (h >> 6);
    h += (h << 2) + (h << 14);
    return h ^ (h >> 16);
}

然后我尝试将它用于 unordered_map 的 hash 参数。 我是否总是需要编写一个 c++ 函子作为包装器才能使用它? 还是有更方便的方法将其作为模板参数传递?

谢谢!

是的,有可能

#include <iostream>
#include <unordered_map>

size_t Wang_Jenkins_hash(size_t h) {
    h += (h << 15) ^ 0xffffcd7d;
    h ^= (h >> 10);
    h += (h << 3);
    h ^= (h >> 6);
    h += (h << 2) + (h << 14);
    return h ^ (h >> 16);
}

int main() {
    std::unordered_map<size_t, size_t, decltype(&Wang_Jenkins_hash)> m(0, &Wang_Jenkins_hash); 
    return 0;
}

函子可能是最简单的方法。 当您使用免费的 function 时,语法变为

std::unordered_map<std::size_t, std::size_t, decltype(&Wang_Jenkins_hash)>

但这只是您需要的一半。 Since we are using a function pointer type we need to pass to the map the function to use, and to do that you have to specify how many initial buckets you want along with the function to actually use. 可以这样做

std::unordered_map<std::size_t, std::size_t, decltype(&Wang_Jenkins_hash)> foo(1024, &Wang_Jenkins_hash);

如果您改为切换到仿函数,则可以将代码更改为

struct Wang_Jenkins_hash
{
    std::size_t operator()(std::size_t)
    {
        h += (h << 15) ^ 0xffffcd7d;
        h ^= (h >> 10);
        h += (h << 3);
        h ^= (h >> 6);
        h += (h << 2) + (h << 14);
        return h ^ (h >> 16);
    }
};

std::unordered_map<std::size_t, std::size_t, Wang_Jenkins_hash> foo;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM