[英]How to correctly remove an item from the map by key?
有一個任務:通過鍵從QMap中刪除項目。
我用這段代碼來做。
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";
我得到以下結果:
之前:“ 0”“ 1”“ 2”“ 3”“ 4”“ 5”
之后:“ 0”“ 1”“ 2”“”“ 4”
但我希望結果是:
之前:“ 0”“ 1”“ 2”“ 3”“ 4”“ 5”
后:
“ 0”“ 1”“ 2”“ 4”“ 5”
請告訴我怎么了?
關於QMap::value(const Key)
:
返回與鍵關聯的值。
如果地圖不包含帶有鍵的項,則該函數返回 默認構造的值 。 如果映射中有多個鍵項,則返回最近插入的一項的值。
映射的初始大小為6,在刪除key = 3
項之后,映射的大小為5。您從0迭代到5,然后value(3)
構造默認的QString對象,因為以3為鍵的項不存在,即這就是為什么您將“”視為輸出。 因此,您的問題是迭代次數與地圖中的鍵不匹配。
使用迭代器打印地圖:
for (auto it = map.begin(); it != map.end(); ++it)
cout << it.value() << endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.