如何在unordered_map中使用lambda函数作为哈希函数?

Han*_*nXu 35 c++ c++11

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

zch*_*zch 50

#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); 
}
Run Code Online (Sandbox Code Playgroud)

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

正如@mmocny在评论中建议的那样,如果你真的想摆脱它,也可以定义make函数来启用类型推导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);
            });
}
Run Code Online (Sandbox Code Playgroud)

  • 或者,为类型推导编写一个make_unordered_hash模板化函数.实际上还有一个C++提案可以更一般地解决这个问题http://isocpp.org/files/papers/n3602.html (9认同)