如何使用lambda函数作为散列函数在unordered_map? [英] How to use lambda function as hash function in unordered_map?

查看:155
本文介绍了如何使用lambda函数作为散列函数在unordered_map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用lambda函数作为自定义哈希函数的unordered_map在C ++ 11?如果是,语法是什么?

I wonder if it is possible to use lambda function as custom hash function for unordered_map in C++11? If so, what is the syntax?

推荐答案

#include<unordered_map>
#include<string>

int main() {
    auto my_hash = [](std::string const& foo) {
        return std::hash<std::string>()(foo);
    };

    std::unordered_map<std::string, int, decltype(my_hash)> my_map(10, my_hash); 
}



您需要将lambda对象传递给 unordered_map 构造函数,因为lambda类型不是默认可构造的。

You need to pass lambda object to unordered_map constructor, since lambda types are not default constructible.

由于@mmocny在注释中建议,它也可以定义make函数来启用类型扣除,如果你真的想摆脱 decltype

As @mmocny suggested in comment, it's also possible to define make function to enable type deduction if you really want to get rid of decltype:

#include<unordered_map>
#include<string>

template<
        class Key,
        class T,
        class Hash = std::hash<Key>
        // skipped EqualTo and Allocator for simplicity
>
std::unordered_map<Key, T, Hash> make_unordered_map(
        typename std::unordered_map<Key, T, Hash>::size_type bucket_count = 10,
        const Hash& hash = Hash()) {
    return std::unordered_map<Key, T, Hash>(bucket_count, hash);
}

int main() {
    auto my_map = make_unordered_map<std::string, int>(10,
            [](std::string const& foo) {
                return std::hash<std::string>()(foo);
            });
}

这篇关于如何使用lambda函数作为散列函数在unordered_map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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