map,vector等容器的循环删除不能用普通的方法删除:

  1. for(auto p=list.begin();p!=list.end();p++)
  2. list.erase(p);

类似的方式,会出错的,不信你调试试试 🙂

这里使用了一个` iterator` 的一个自增/自减 ,来巧妙的实现了, 删除当前的`iterator,` 但是又给当前的`iterator`赋值为其下一个的操作,不至于删除后,当前的 `iterator` 就失效了!

 代码:

  1. 1 #include <iostream>
  2. 2 #include <vector>
  3. 3 #include <map>
  4. 4 using namespace std;
  5. 5
  6. 6 int main()
  7. 7 {
  8. 8 const char* strs[] = {
  9. 9 "str1",
  10. 10 "str2",
  11. 11 "str3",
  12. 12 "str4",
  13. 13 "str5",
  14. 14 "str6",
  15. 15 "str7",
  16. 16 "str8",
  17. 17 "str9",
  18. 18 "str10"
  19. 19 };
  20. 20 cout << "Hello World\n";
  21. 21
  22. 22 map<string, string> list;
  23. 23 vector<string> arr;
  24. 24 for (int i = 9; i>=0; i--) {
  25. 25 list.emplace(std::make_pair(strs[i], strs[i]));
  26. 26 arr.emplace_back(strs[i]);
  27. 27 }
  28. 28 auto pos = list.end();
  29. 29 pos--;//取得倒数第一个的位置
  30. 30 while (pos!= list.end() && list.size()>3)
  31. 31 list.erase(pos--);//关键在这里
  32. 32 while (arr.size() > 3)
  33. 33 arr.erase(--arr.end());//关键在这里
  34. 34 for (auto s : list) {
  35. 35 cout << s.first.data() << " " << s.second.data() << "\n";
  36. 36 }
  37. 37 for (auto s : arr) {
  38. 38 cout << s.data()<< "\n";
  39. 39 }
  40. 40 return 0;
  41. 41 }

  输出:

  1. Hello World
  2. str1 str1
  3. str10 str10
  4. str2 str2
  5. str10
  6. str9
  7. str8

 

使用一个` iterator` 的一个自增/自减 ,来巧妙的实现了:

删除当前的`iterator`,又有给当前的`iterator`赋值为其下一个的位置,不至于删除后,当前的 `iterator` 就失效了!

代码参考:

  1. //vector的删除某些项
  2. //vector<T> list;
  3. auto& it = list.begin();
  4. while (it!=list.end()){
  5. if (it->Code == `Code`)
  6. it = list.erase(it);//返回下一个元素iterator
  7. else
  8. it++;
  9. }
  10. //map的删除某些项
  11. // map<string,T> mapA;
  12. 1.直接删除指定项
  13. mapA.erase(str1);
  14. 2.直接删除指定位置的项
  15. mapA.erase(pos);
  16. 3.删除符合条件的项
  17. for (auto it = _chwList.begin(); it != _chwList.end();) {
  18. if (it->second->Code==`Code`)
  19. _chwList.erase(it++);
  20. else
  21. it++;
  22. }

 

版权声明:本文为lzpong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/lzpong/p/6963300.html