How to configure a hash structure?

In C ++, there is a default hash function std::hash<T> for the simplest types, for example std::string , int , etc. I believe that these functions have good entropy and the corresponding random variable distribution is statistically uniform. If this is not so, then let it pretend to be so.

Then I have a structure:

 struct CustomType { int field1; short field2; string field3; // ... }; 

I want to use it using separate hashes of some of its fields, say std::hash(field1) and std::hash(field2) . Both hashes are in the set of possible values ​​of type size_t .

What is a good hash function that can combine both of these results and map them back to size_t ?

+6
source share
2 answers

boost::hash_combine really good for hashing different fields.

If you don't have a boost library, you can use this:

 template <class T> inline void hash_combine(std::size_t & s, const T & v) { std::hash<T> h; s^= h(v) + 0x9e3779b9 + (s<< 6) + (s>> 2); } struct S { int field1; short field2; std::string field3; // ... }; template <class T> class MyHash; template<> struct MyHash<S> { std::size_t operator()(S const& s) const { std::size_t res = 0; hash_combine(res,s.field1); hash_combine(res,s.field2); hash_combine(res,s.field3); return res; } }; 

And then probably std::unordered_set<S> s; etc.

+5
source

boost::hash_combine is what can help you here:

 namespace std { template <> struct hash<CustomType> { std::size_t operator()(const CustomType& c) const { std::size_t result = 0; boost::hash_combine(result, field1); boost::hash_combine(result, field2); return result; } }; } 

Refer to boost document here .

+3
source

Source: https://habr.com/ru/post/955291/


All Articles