// 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 );
}