本文介绍了如何为 QSet<SomeClass*> 编写 qHash容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的应用程序中实现一组集合.将 QSet 与自定义类一起使用需要提供 qHash() 函数和 operator==.

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==.

代码如下:

    class Custom{
        int x;
        int y;
        //some other irrelevant here
    }
    inline uint qHash(Custom* c){
        return (qHash(c->x) ^ qHash(c->y));
    }
    bool operator==(Custom &c1, Custom &c2){
        return ((c1.x==c2.x) && (c1.y == c2.y));
    }

    //now I can use: QSet<Custom*>

如何实现 qHash(QSet),以便能够使用 QSet<;QSet<SomeClass*>>?

How can I implement qHash(QSet<Custom*>), to be able to use QSet< QSet<SomeClass*> >?

补充问题:在我的应用程序中,集合集"最多可以包含 15000 个集合.每个子集最多有 25 个自定义类指针.如何保证 qHash(QSet<Custom*>) 足够唯一?

Additional question:In my application the "set of sets" can contain up to 15000 sets. Each subset up to 25 Custom class pointers. How to guarantee that qHash(QSet<Custom*>) will be unique enough?

推荐答案

散列容器的常用方法是组合所有元素的散列.Boost 提供 hash_combine 和 hash_range以此目的.这应该让您了解如何为 qHash 的结果实现这一点.

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.

所以,给定 qHash for Custom:

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

这篇关于如何为 QSet&lt;SomeClass*&gt; 编写 qHash容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-11 17:57