简体   繁体   English

如何正确地从地图上删除一个项目?

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

There is such a task: to delete items from the QMap by key. 有一个任务:通过键从QMap中删除项目。

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" 之前:“ 0”“ 1”“ 2”“ 3”“ 4”“ 5”


After: "0" "1" "2" "" "4" 之后:“ 0”“ 1”“ 2”“”“ 4”

But I expect the result to be: 但我希望结果是:

Before: "0" "1" "2" "3" "4" "5" 之前:“ 0”“ 1”“ 2”“ 3”“ 4”“ 5”


After: 后:

"0" "1" "2" "4" "5" “ 0”“ 1”“ 2”“ 4”“ 5”

Please tell me what is wrong? 请告诉我怎么了?

Reference about QMap::value(const Key) : 关于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. 映射的初始大小为6,在删除key = 3项之后,映射的大小为5。您从0迭代到5,然后value(3)构造默认的QString对象,因为以3为键的项不存在,即这就是为什么您将“”视为输出。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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