如何为QSet写< SomeClass *>容器? [英] How to write qHash for a QSet<SomeClass*> container?
问题描述
我需要在我的应用程序中实现一组集合。
使用QSet和自定义类需要提供一个 qHash()
函数和运算符==
。 / p>
代码如下:
class Custom {
int x;
int y;
//其他不相关的
}
inline uint qHash(Custom * c){
return(qHash(c-> x)^ qHash(c-> y ));
}
bool operator ==(Custom& c1,Custom& c2){
return((c1.x == c2.x)&& = c2.y));
}
//现在我可以使用:QSet< Custom *>如何实现 qHash(QSet< Custom *>) ,以能够使用 QSet< QSet< SomeClass *> >
?
编辑:
其他问题:
我的应用程序的套集最多可以包含15000套。每个子集最多25个自定义类指针。如何保证 qHash(QSet< Custom *>)
将足够独特?
解决方案哈希容器的一种常见方法是组合所有元素的哈希值。 Boost提供 hash_combine和hash_range 以此目的。这应该给你一个想法如何实现这个结果你的 qHash
。
code> qHash
for 自定义
: uint qHash(const QSet< Custom *>& c){
uint seed = 0;
for(auto x:c){
seed ^ = qHash(x)+ 0x9e3779b9 +(seed <6)+(seed>> 2);
}
return seed;
}
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==
.
The code is as follows:
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*>
How can I implement qHash(QSet<Custom*>)
, to be able to use QSet< QSet<SomeClass*> >
?
Edit:
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?
解决方案 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;
}
这篇关于如何为QSet写< SomeClass *>容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!