Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QHash ordered, not because



  • Good afternoon, I have the following code and I returned the tickets I ordered alphabetically, like a QMap, any idea of the problem?, Thanks.

    @
    QHash<QString, int> hash;
    hash["one"] = 1;
    hash["three"] = 3;
    hash["seven"] = 7;

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

    @

    exit:
    "one" : 1
    "seven" : 7
    "three" : 3

    [edit: added missing coding tags @ SGaist]



  • So you are wondering why the items of a QHash are "out of order"?

    It's a fundamental property of a Hash map that items are stored in an arbitrary order. That's the price you have to pay for the fast lookup that the Hash map provides. If you need the keys to be stored in ascending order, use a QMap.

    --

    From the manual:

    bq. When iterating over a QMap, the items are always sorted by key. With QHash, the items are arbitrarily ordered.


Log in to reply