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 }