map,vector 等容器内容的循环删除问题(C++)
map,vector 等容器内容的循环删除问题(C++)
map,vector等容器的循环删除不能用普通的方法删除:
- for(auto p=list.begin();p!=list.end();p++)
- list.erase(p);
类似的方式,会出错的,不信你调试试试 🙂
这里使用了一个` iterator` 的一个自增/自减 ,来巧妙的实现了, 删除当前的`iterator,` 但是又给当前的`iterator`赋值为其下一个的操作,不至于删除后,当前的 `iterator` 就失效了!
代码:
- 1 #include <iostream>
- 2 #include <vector>
- 3 #include <map>
- 4 using namespace std;
- 5
- 6 int main()
- 7 {
- 8 const char* strs[] = {
- 9 "str1",
- 10 "str2",
- 11 "str3",
- 12 "str4",
- 13 "str5",
- 14 "str6",
- 15 "str7",
- 16 "str8",
- 17 "str9",
- 18 "str10"
- 19 };
- 20 cout << "Hello World\n";
- 21
- 22 map<string, string> list;
- 23 vector<string> arr;
- 24 for (int i = 9; i>=0; i--) {
- 25 list.emplace(std::make_pair(strs[i], strs[i]));
- 26 arr.emplace_back(strs[i]);
- 27 }
- 28 auto pos = list.end();
- 29 pos--;//取得倒数第一个的位置
- 30 while (pos!= list.end() && list.size()>3)
- 31 list.erase(pos--);//关键在这里
- 32 while (arr.size() > 3)
- 33 arr.erase(--arr.end());//关键在这里
- 34 for (auto s : list) {
- 35 cout << s.first.data() << " " << s.second.data() << "\n";
- 36 }
- 37 for (auto s : arr) {
- 38 cout << s.data()<< "\n";
- 39 }
- 40 return 0;
- 41 }
输出:
- Hello World
- str1 str1
- str10 str10
- str2 str2
- str10
- str9
- str8
使用一个` iterator` 的一个自增/自减 ,来巧妙的实现了:
删除当前的`iterator`,又有给当前的`iterator`赋值为其下一个的位置,不至于删除后,当前的 `iterator` 就失效了!
代码参考:
- //vector的删除某些项
- //vector<T> list;
- auto& it = list.begin();
- while (it!=list.end()){
- if (it->Code == `Code`)
- it = list.erase(it);//返回下一个元素iterator
- else
- it++;
- }
- //map的删除某些项
- // map<string,T> mapA;
- 1.直接删除指定项
- mapA.erase(str1);
- 2.直接删除指定位置的项
- mapA.erase(pos);
- 3.删除符合条件的项
- for (auto it = _chwList.begin(); it != _chwList.end();) {
- if (it->second->Code==`Code`)
- _chwList.erase(it++);
- else
- it++;
- }