Search code examples
qtkey-valuekeyvaluepairqmap

How to rename Key for QMap?


I have this QMap<int, myDB> myTable like this

(1, {something0})
(3, {something1})
(5, {something2})
(8, {something3})

How can I change Key for myTable with first key begin from 0?

(0, {something0})
(1, {something1})
(2, {something2})
(3, {something3})

Solution

  • You can not change the key directly in the original map, instead create an other map, assign the values to the other map with reorganized key, then use QMap::swap to replace the original map items. The snippets will look like

    //Make sure myDB is assignable
    QMap<int, myDB> other;
    QList<int> keys = myTable.uniqueKeys();
    for (int k = 0; k < keys.length(); k++) {
        int key = keys[k];
    
        //We're using insertMulti in case
        //we have multiple values associated to single key
        QList<myDB> values = myTable.values(key);
        for (int j = 0; j < values.length(); j++) {
            other.insertMulti(k, values.at(j));
        }
    }
    myTable.swap(other);