Question

I want to create QHash with three arguments:

QHash <int, QString, float> myhash;

I know that I have to use nested QHash, so I did:

QHash <int, QHash<QString, float> > myhash;

But I could not figure out how I can insert values to myhash. I tried to create another Qhash and insert this into my myhash, but I does not make any sence, since I have exactly 1 pair data for one key. What I want basically is :

0, "string1", 1.5
1, "string2", 1.2 etc.

How I can create efficiently (in terms of lookup time (the reason I am using QHash)) the above arrays. And how to insert values afterwards.

Thanks forward.

Was it helpful?

Solution

With QHash <int, QHash<QString, float> > myhash;, you can simply do this to set values:

myhash[42]["fortytwo"] = 42.42;

You can use the same syntax to access elements, but note that when accessed with non-const operator[], these entries will actually be created in the hash. So it's often better to use value() method:

if (myhash.value(43).value("fortytwo") >= 42) { /*...*/ }

Note that for QHash and QMap, accessing key which is not in the map is ok, default constructed value is returned in that case. Above for first it means and empty hash, and for second, value 0.0f.


To compare this to the method of using QPair from the other answer, this has the particular advantage that you can access elements by "rows" easily, if it matters for your use case (just make sure you have the nested hashes in the right order). Also, with this method, you could use different container for different dimensions, like if you need one dimension to be sorted use QMap (which is sorted by key) for that, and QHash (which is more efficient) for the dimension which doesn't need sorting. Additionally, you can have any number of dimensions easily, just add more nested containers.

On the other hand, if the key is logically a pair of values which are never separated, and data is not really (from programming perspective) organized as a two-dimensional table, then using QPair for key is probably better.


Unrelated to the question: to improve efficiency, in Qt 5 and C++11 you could use QStringLiteral("fortytwo") to have the QString created already at compile time.

OTHER TIPS

Use a QPair as your key:

QHash<QPair<int,QString>,float> myhash;

Insert values:

myhash.insert(QPair<int,QString>(1,"string1"),12.);

or

QPair<int,QString> p(1,"string1");

myhash[p] = 12.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top