1

There is such a task: to delete items from the QMap by key.

I do this with this code.

QMap <int, QString> map;
map.insert(0, "0");
map.insert(1, "1");
map.insert(2, "2");
map.insert(3, "3");
map.insert(4, "4");
map.insert(5, "5");

qDebug() << "Before:";
for (auto i = 0; i < map.size(); i++)
    qDebug() << map.value(i) << "\t";
qDebug() << "--------------";

map.remove(3);

qDebug() << "After:";
for (auto i = 0; i < map.size(); i++)
    qDebug() << map.value(i) << "\t";

I have the following result:

Before: "0" "1" "2" "3" "4" "5"


After: "0" "1" "2" "" "4"

But I expect the result to be:

Before: "0" "1" "2" "3" "4" "5"


After:

"0" "1" "2" "4" "5"

Please tell me what is wrong?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Konstantin
  • 35
  • 1
  • 5
  • 1
    Try function map.erase(3) may help you https://stackoverflow.com/questions/799314/difference-between-erase-and-remove – Gurult Jan 30 '19 at 06:55

1 Answers1

4

Reference about QMap::value(const Key):

Returns the value associated with the key key.

If the map contains no item with key key, the function returns a default-constructed value. If there are multiple items for key in the map, the value of the most recently inserted one is returned.

Initial size of map is 6, after removing item with key = 3 size of map is 5. You are iterating from 0 up to 5, then value(3) constructs default QString object because item with 3 as key doesn't exist, that is why you see "" as output. So your issue is that the number of iteration doesn't match to key in your map.

Print map using iterators:

for (auto it = map.begin(); it != map.end(); ++it)
  cout << it.value() << endl;
rafix07
  • 20,001
  • 3
  • 20
  • 33
  • 1
    Also, the `QMap` iterator implements `operator*` to return the item's value component (unlike `std::map`'s iterator): `cout << *it << endl;` – Remy Lebeau Jan 30 '19 at 07:00
  • Better a `for (auto it = map.constBegin(); it != map.constEnd(); ++it)` here – Moia Jan 30 '19 at 07:53
  • @Moia a range-for loop would be even better: `for (auto &value : map) cout << value << endl;` – Remy Lebeau Jan 30 '19 at 19:49
  • @RemyLebeau I agree. i was thinking about printing `it.key() << it.value()` where the iterator is usefult but he actually didn't write that so for range loop is definitely better – Moia Jan 31 '19 at 09:27