C ++ resentment Note 9 -- vector. Erase and set. Erase

Source: Internet
Author: User
// Use erase to clear the content in the vector and set respectively # include <vector> # include <string> # include <set> using namespace STD; void fnvec () {vector <wstring> VEC; Vec. push_back (L "AAA"); Vec. push_back (L "BBB"); Vec. push_back (L "CCC"); Vec. push_back (L "DDD"); Auto it = Vec. begin (); While (VEC. size () {auto T = it; it ++; Vec. erase (t) ;}} void fnset () {set <wstring> S; S. insert (L "AAA"); S. insert (L "BBB"); S. insert (L "CCC"); S. insert (L "DDD"); Auto it = S. begin (); While (S. size () {auto T = it; it ++; S. erase (t) ;}} void main () {fnset (); fnvec ();}

Fnset will delete all the elements in the set, but fnvec will cause the program to crash.
The reason is that when fnvec calls Vec. Erase (t), the elements behind t slide forward, and the iterator pointing to these elements is also affected. In fnset, if erase is called, the elements do not slide, because the set is not as random as the vector can be accessed, and the iterator is not affected, so it can be deleted normally.

PS: the code in the while loop can be simplified:
While (S. Size ())
{
S. Erase (it ++ );
}

Because a temporary variable has been assigned to the iterator operator ++:

_ Myiter operator ++ (INT)
{// Postincrement
_ Myiter _ TMP = * this;
+ + * This;
Return (_ TMP );
}

Related Article

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.