3

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})
songvan
  • 369
  • 5
  • 21
  • What pattern do you use when replacing one key with the other key, i.e. `1` replaced by `0`, `1` should be replaced by what? – putu Jun 08 '17 at 10:59
  • @putu: actually I just want to set all the key ascending, like reorganize, begin from 0 – songvan Jun 08 '17 at 11:03
  • In `QMap`, items are sorted by key not by the order of data insertion, but in your question, I think you want to reorganized the map according to data insertion order, which is in this case would be difficult (or impossible). If you just want to reorganize a map having key `1,3,5,8` to `0,1,2,3`, it will be easy. – putu Jun 08 '17 at 11:12
  • I just want to rename the Key: `1`->`0`, `3`->`1`, `5`->`2` and `8`->`3` – songvan Jun 08 '17 at 11:16
  • Edit the question as so, since in the current question your key order is `1,5,3,8` not `1,3,5,8`. – putu Jun 08 '17 at 11:28
  • thanks. I have edited. Do you have solution for renaming them? – songvan Jun 08 '17 at 11:36
  • 1
    I guess, you could iterate over the map and replace the entries by new ones (where the new key is a simple counter). In case, the new entries could be inserted into a second `QMap` instance which could be swapped with the original afterwards. However, this solution depends on the `myDB` type i.e. whether its copyable. (If not, things are probably more complicated.) – Scheff's Cat Jun 08 '17 at 11:47

1 Answers1

3

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);
putu
  • 6,218
  • 1
  • 21
  • 30