PDA

View Full Version : QHash ordered by value



Lele
11th February 2008, 09:24
Hi all,
I'd need to have a QHash where the elements are ordered by a certain filed inside the value.



struct MyData
{
MyData(): bitmap(0), weight(0) {}
MyData(qint64 b, qint32 w) : bitmap(b), weight(w) {}

qint64 bitmap;
qint32 weight;
};

QHash<qint32, MyData> mCurrentCache;


In my case I would like to order the elements depending on MyData::weight.
Is there a smart way to do that or do I have to resort to an additional QHash<qint32, qint32> as a look up table?

Thanks for any help
bye

marcel
11th February 2008, 09:29
1. QHash is not a data structure that can be sorted.
2. Why don't you use the weight as a key? Like this:


mCurrentCache[myDataObject.weight] = myData;

marcel
11th February 2008, 09:32
Also, you need to declare MyData as a qt metatype, to be able to use it in a template container.


Q_DECLARE_METATYPE(MyStruct)


Add this right after the struct definition.

Lele
11th February 2008, 09:32
Thanks for the quick reply.
I don't use the "weight" as a key because I need the key for other purposes.
The other thing I could do is to use a QMap<weight, key> knowing that the insert there preserve the order. But I though there was a smarter way to have only one QHash.
bye

marcel
11th February 2008, 09:37
You could create another class to be used as a key, just like in the QHash example:


class MyKey
{
public:
MyKey();
MyKey(const qint32& key, const qint32& weight);

//add == operator
//add uint qHash(const MyKey& k);
private:
qint32 weight;
qint32 key;
};



You could then use MyKey as a QHash key.

Lele
11th February 2008, 09:46
Interesting, would it be enought to redefine the operator > to order by the weight filed?
The only problem is that with this I won't have a fast look up on the key, probably I could redefine even the contains method and the [] operator.....

marcel
11th February 2008, 10:05
As I told you before, QHash is not sorted, so implementing the > or < operators would make no sense.

jpn
11th February 2008, 10:30
Why not a single map:

QMap<qint32, qint64> bitmaps;
where key is weight and value is bitmap identifier or whatever is it?