vector和map的erase()函數

來源:互聯網
上載者:User

vector迴圈刪除的時候,erase(it)會返回下一個迭代器的地址,保險的做法是賦值給it 即 it= erase(it)

這是vector的內部機制所造成的,所以對vector進行erase的時候特別注意迭代器是否會失效!

map則可以直接erase(it++);

vector和map都不能將it++寫在for迴圈中,而在迴圈體內erase(it)!

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 << " ";
    }  

    // 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的整數倍刪除後應該剩下i3";
    cout <<"m size = "<<m.size() <<endl;

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.