我需要在我的应用程序中实现一组集合。
将QSet与自定义类一起使用需要提供qHash()
函数和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<Custom*>)
以便能够使用QSet< QSet<SomeClass*> >
?编辑:
附加问题:
在我的应用程序中,“套组”最多可以包含15000套。每个子集最多25个自定义类指针。如何保证
qHash(QSet<Custom*>)
足够唯一? 最佳答案
散列容器的一种常见方法是组合所有元素的哈希。 Boost为此提供了hash_combine and hash_range。这应该使您知道如何针对qHash
的结果实现此功能。
因此,给定qHash
的Custom
:
uint qHash(const QSet<Custom*>& c) {
uint seed = 0;
for(auto x : c) {
seed ^= qHash(x) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}