Cyclic removal of container content such as map,vector (C + +)
Map,vector and other containers can not be deleted by the normal method:
for (Auto P=list.begin ();p!=list.end ();p + +) list.erase (p);
A similar way, will be wrong, do not believe you try to debug:)
Here used a ' iterator ' of a self-increment/decrement, to cleverly implement, delete the current ' iterator, ' but have given the current ' iterator ' assignment for its next operation, not deleted, the current ' iterator ' will expire!
Code:
1#include <iostream>2#include <vector>3#include <map>4 using namespacestd;5 6 intMain ()7 {8 Const char * strs[] = {9 "str1",Ten "str2", One "STR3", A "STR4", - "STR5", - "STR6", the "STR7", - "Str8", - "STR9", - "Str10" + }; -cout <<"Hello world\n"; + Amap<string,string>list; atvector<string>arr; - for(inti =9; i>=0; i--) { - List.emplace (Std::make_pair (Strs[i], strs[i])); - Arr.emplace_back (Strs[i]); - } -Auto pos =list.end (); inpos--; //Get the first place in the countdown - while(pos!= list.end () && list.size () >3) toList.erase (pos--); //Key here + while(Arr.size () >3) -Arr.erase (--arr.end ()); //Key here the for(Auto s:list) { *cout << s.first.data () <<" "<< S.second.data () <<"\ n"; $ }Panax Notoginseng for(Auto S:arr) { -cout << s.data () <<"\ n"; the } + return 0; A}
Output:
Hello Worldstr1 str1str10 str10str2 str2str10str9str8
Cyclic removal of container content such as map,vector (C + +)