I am compiling below code in QT version 4.8 as well as in 5.12.9 .
QHash<QString, int> m_userDataHash;
m_userDataHash.insert("white", 1);
m_userDataHash.insert("yellow", 3);
m_userDataHash.insert("lightblue", 5);
m_userDataHash.insert("darkblue", 7);
m_userDataHash.insert("pink", 9);
m_userDataHash.insert("red", 11);
m_userDataHash.insert("green", 13);
m_userDataHash.insert("black", 15);
m_userDataHash.insert("grey", 17);
QHashIterator<QString, int> i(m_userDataHash);
while (i.hasNext())
{
i.next();
ui->ColorCombo->addItem(i.key());
}
This code is behaving differently as the order of insertion is different in different qt version.
In Qt 5.12.9
In Qt 4.8
How can I solve this problem? Why is this happening?
I checked the QHash documentation but could not figure out anything. https://doc.qt.io/qt-5/qhash.html#insert
QT documentation states that:
When iterating over a QMap, the items are always sorted by key. With QHash, the items are arbitrarily ordered.
That is an expected behavior for a hash function. They do not store items in any order, but instead you can get any item fast enough O(1). Maps store the keys the tree, you can iterate them in order, but the lookup is log(N).
The implementation of the hash function might have changed and you get different order. That is what happening here.
If there are few items in the map it may be faster than the hash. Probably you can just replace QHash with QMap.
If you've got lots of items and need a very fast lookup (so QHash is your best option), then you can separately store the ordered keys in the vector and use it for iterating.