Home > Back-end >  supply custom hashing/equal func to unordered_map
supply custom hashing/equal func to unordered_map

Time:05-26

I have this following code:

typedef std::size_t (*hash_func)(const sp_movie& movie);
typedef bool (*equal_func)(const sp_movie& m1,const sp_movie& m2);

typedef std::unordered_map<sp_movie, double, hash_func, equal_func> rank_map;

These are my actual functions I want to use in my unordered_map:

std::size_t sp_movie_hash(const sp_movie& movie);
bool sp_movie_equal(const sp_movie& m1,const sp_movie& m2);

How ever, I can't create a rank_map with my custom hash function and equal function I made. I don't want to do it using classes for hash and equal, I just want to pass to the unordered_map the functions I've made.

I tried this code:

rank_map check (sp_movie, double, sp_movie_hash, sp_movie_equal);
rank_map check (sp_movie_hash, sp_movie_equal);

both of them didn't work

CodePudding user response:

The only suitable constructor is the one that also accepts bucket_count. Passing 0 seems to work:

rank_map check(0, sp_movie_hash, sp_movie_equal);

However, if you don't want to select the hash/equality functions at runtime, you should make them into functors (default-constructible classes). If you don't want to write the classes yourself, you can wrap the functions (surprisingly) in std::integral_constant:

using rank_map = std::unordered_map<sp_movie, double,
    std::integral_constant<decltype(&sp_movie_hash), sp_movie_hash>,
    std::integral_constant<decltype(&sp_movie_equal), sp_movie_equal>
>;

This makes your hash maps default-constructible, and removes the overhead of storing function pointers.

  • Related