//test
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<int, string> Inventory;
Inventory[1] = "Sword";
Inventory[2] = "Armor";
Inventory[3] = "Shield";
map<int, string>::iterator iter;
for (iter = Inventory.begin(); iter != Inventory.end(); ++iter)
cout << (*iter).first << " - " << (*iter).second << "\n";
iter == Inventory.find(2);
Inventory.erase(iter);
cout << "\n" << Inventory.count(2) << "\n";
iter == Inventory.find(2);
cout << "\n" << (*iter).first << " - " << (*iter).second.size() << "\n\n";
if (Inventory.find(2) == Inventory.end())
cout << "\nNot found.\n";
for (iter = Inventory.begin(); iter != Inventory.end(); ++iter)
cout << (*iter).first << " - " << (*iter).second << "\n";
cout << "\n" << Inventory.size() << "\n";
system("PAUSE");
return EXIT_SUCCESS;
}
这是我运行程序时得到的结果:
1 - 剑
2 - 护甲
3 - 盾
1
2 - 1968772512
1 - 剑
3 - 盾
2
所以我有点困惑为什么键'2'没有被完全删除。
Inventory.count(2)返回1,这意味着密钥'2'仍然在某处的库存中挥之不去?
显然,在删除键'2'后,find()仍会返回该键值的迭代器?
erase()究竟是如何工作的?
答案 0 :(得分:4)
iter == Inventory.find(2);
不是作业,我猜你打算这样做:
iter = Inventory.find(2);