How to properly hash the custom struct?

前端 未结 2 1738
轮回少年
轮回少年 2020-12-17 17:50

In the C++ language there is the default hash-function template std::hash for the most simple types, like std::string, int, e

相关标签:
2条回答
  • 2020-12-17 18:30

    boost::hash_combine is really good one to hash different fields.

    If you don't have 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

    0 讨论(0)
  • 2020-12-17 18:31

    boost::hash_combine is something that could help you out 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;
        }
    };
    }
    

    See the boost doc here.

    0 讨论(0)
提交回复
热议问题