Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

c++ - How to use lambda function as hash function in unordered_map?

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?

question from:https://stackoverflow.com/questions/15719084/how-to-use-lambda-function-as-hash-function-in-unordered-map

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
#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); 
}

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...