简体   繁体   中英

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})

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM