Detailed resolution of the erase of function between vector and map

  • 2020-04-02 01:39:26
  • OfStack

When the vector loop is deleted, the erase(it) returns the address of the next iterator. The safe way to do this is to assign the value to it, i.e., it= erase(it)

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

Map can erase directly (it++);

Neither vector nor map can write it++ in the for loop, and erase(it)! In the loop body.


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 << " ";
    }   
    //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 Integer multiples of should be left after deletion i3";
    cout <<"m size = "<<m.size() <<endl;
}


Related articles: