map,vector 等容器內容的循環刪除問題(C++)

 

 map,vector 等容器內容的循環刪除問題(C++)

 map,vector等容器的循環刪除不能用普通的方法刪除:ios

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

相似的方式,會出錯的,不信你調試試試 :)spa

這裏使用了一個` iterator` 的一個自增/自減 ,來巧妙的實現了, 刪除當前的`iterator,` 可是又給當前的`iterator`賦值爲其下一個的操做,不至於刪除後,當前的 `iterator` 就失效了!調試

 代碼:code

 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 }

  輸出:blog

Hello World
str1 str1
str10 str10
str2 str2
str10
str9
str8

 

使用一個` iterator` 的一個自增/自減 ,來巧妙的實現了:string

刪除當前的`iterator`,又有給當前的`iterator`賦值爲其下一個的位置,不至於刪除後,當前的 `iterator` 就失效了!it

代碼參考:io

//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++;
    }
相關文章
相關標籤/搜索