How to write qHash for a QSet container?

后端 未结 2 708
执笔经年
执笔经年 2020-12-17 23:06

I need to implement a set of sets in my application. Using QSet with a custom class requires providing a qHash() function and an operator==.

<
相关标签:
2条回答
  • 2020-12-17 23:24

    A common way to hash containers is to combine the hashes of all elements. Boost provides hash_combine and hash_range for this purpose. This should give you an idea how to implement this for the results of your qHash.

    So, given your qHash for Custom:

    uint qHash(const QSet<Custom*>& c) {
      uint seed = 0;
    
      for(auto x : c) {
        seed ^= qHash(x) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
      }
    
      return seed;
    }
    
    0 讨论(0)
  • 2020-12-17 23:34

    You cannot implement qHash with boost::hash_range/boost::hash_combine (which is what pmr's answer does, effectively), because QSet is the Qt equivalent of std::unordered_set, and, as the STL name suggests, these containers are unordered, whereas the Boost Documentation states that hash_combine is order-dependent, ie. it will hash permutations to different hash values.

    This is a problem because if you naively hash-combine the elements in stored order you cannot guarantee that two sets that compare equal are, indeed, equal, which is one of the requirements of a hash function:

    For all x, y:   x == y => qHash(x) == qHash(y)
    

    So, if your hash-combining function needs to produce the same output for any permutation of the input values, it needs to be commutative. Fortunately, both (unsigned) addition and the xor operation just fit the bill:

    template <typename T>
    inline uint qHash(const QSet<T> &set, uint seed=0) {
        return std::accumulate(set.begin(), set.end(), seed,
                               [](uint seed, const T&value) {
                                   return seed + qHash(value); // or ^
                               });
    }
    
    0 讨论(0)
提交回复
热议问题