c++qtqmap

How to correctly remove an item from the map by key?


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?


Solution

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