The erase () function of vector and map detailed parsing _c language

Source: Internet
Author: User

When vector loops are removed, erase (IT) returns the address of the next iterator, and the insurance practice is to assign it to the IT it= erase (IT)

This is caused by the vector's internal mechanism, so pay special attention to whether the iterator will fail when the vector is erase!

Map can be directly erase (it++);

Neither vector nor map can write it++ in the For loop, but in the Loop body erase (IT)!

Copy Code code as follows:

void Main ()
{
Vector<int> v;
V.push_back (1);
V.push_back (2);
V.push_back (4);
V.push_back (3);
V.push_back (6);
V.push_back (5);
cout << v.size () <<endl;
Vector<int>::iterator it;
for (it = V.begin (); it!= v.end ();)
{
if (*it% 2 = 0)
V.erase (it++);
it = v.erase (it);
V.erase (IT);
Else
it++;
}
cout << v.size () <<endl;
for (it = V.begin (); it!= v.end (); it++)
{
cout << *it << "";
}

The perfect deletion of map
Map<int, int> m;
M[1] = 1;
M[2] = 2;
M[3] = 4;
M[4] = 3;
M[5] = 5;
M[6] = 6;
cout << "M size =" <<m.size () <<endl;
Map<int, Int>::iterator it1;
for (it1 = M.begin (); It1!=m.end ();)
{
if (it1->second% 2 = 0)
M.erase (it1++);
Else
it1++;
}
cout << "2 of the integer multiple deletion should be left after i3";
cout << "M size =" <<m.size () <<endl;

}

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.