Cyclic removal of container content such as map,vector (C + +)

Source: Internet
Author: User

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 + +)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.