map遍历删除特定项和删除遍历删除所有项

 1 #include <iostream>
 2 #include <map>
 3 #include <string>
 4 
 5 using namespace std;
 6 
 7 int main(void)
 8 {
 9     map<string, string> data;
10 
11     data["a"] = "aaa";
12     data["b"] = "bbb";
13     data["c"] = "ccc";
14     data["d"] = "ddd";
15     data["e"] = "eee";
16     data["f"] = "fff";
17     data["g"] = "ggg";
18 
19     for (map<string, string>::iterator iter = data.begin(); iter != data.end(); ++iter)
20     {
21         cout << iter->first << ", " << iter->second << endl;
22     }
23     cout << "----------------------------" << endl;
24     for (map<string, string>::iterator iter = data.begin(); iter != data.end();)
25     {
26         cout << "execute key: " << iter->first << endl;
27         if ("g" == iter->first)
28         {
29             // windows STL支持返回值返回指向下一个元素指针
30             iter = data.erase(iter);
31         }
32         else
33         {
34             ++iter;
35         }
36     }
37     cout << "----------------------------" << endl;
38     for (map<string, string>::iterator iter = data.begin(); iter != data.end(); ++iter)
39     {
40         cout << iter->first << ", " << iter->second << endl;
41     }
42 }

 

 

 1     for (map<string, string>::iterator iter = data.begin(); iter != data.end();)
 2     {
 3         cout << "execute key: " << iter->first << endl;
 4         if ("g" == iter->first)
 5         {
 6             // windows和g++ STL均支持i自增方式
 7             data.erase(iter++);
 8         }
 9         else
10         {
11             ++iter;
12         }
13     }

 

 

 

 1     for (map<string, string>::iterator iter = data.begin(); iter != data.end();)
 2     {
 3         cout << "execute key: " << iter->first << endl;
 4         if ("g" == iter->first)
 5         {
 6             // windows和g++ STL均支持临时变量的方式,此种方式等效于自增变量方式
 7             map<string, string>::iterator copy = iter;
 8             ++iter;
 9             data.erase(copy);
10         }
11         else
12         {
13             ++iter;
14         }
15     }

 

转载于:https://www.cnblogs.com/itpoorman/p/4434692.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值