5

Is it possible to loop a QHash by the insert order? The method below seem to loop the hash by some other factor:

QHashIterator<QString, QString> i(hash);
while (i.hasNext()) {
    i.next();
    qDebug() << i.key() << ": " << i.value();
}

EDIT:

I figured it was impossible with QHash but what should I use instead?

demonplus
  • 5,613
  • 12
  • 49
  • 68
Dennis
  • 3,448
  • 8
  • 38
  • 45

3 Answers3

13

From QHash documentation,

QHash is unordered, so an iterator's sequence cannot be assumed to be predictable. If ordering by key is required, use a QMap

So it is not possible.

If you want ordering based on the keys, use QMap instead..

Hope it helps..

Edit:

If you don't need Key and Value Logical mapping and just their values, you can use

QList<QPair<QString,QString>> pairs;

For e.g:

The first value can be obtained by

QString firstValue = pairs.at(0).first;

Similarly for the second value in the QPair,

QString secondValue = pairs.at(0).second;

And you can iterate over the QList to retrieve the elements in the inserted order..

Random Citizen
  • 1,272
  • 3
  • 14
  • 28
liaK
  • 11,422
  • 11
  • 48
  • 73
1

QHash doesn't remember your insert order. It is designed for fast random access. The order you get with the iterator is arbitrary.

deinst
  • 18,402
  • 3
  • 47
  • 45
0

If you only insert elements (no element removal) in the QHash you could use an array/list in parallel. It is not a very elegant solution but what you want cannot be achieved with QHash container only.

INS
  • 10,594
  • 7
  • 58
  • 89