STL中map/vector的刪除元素操作

    在我們使用C++中的STL的時候,可以使用迭代器iterator進行遍歷,但是當我們通過iterator對vector和map刪除元素的時候,要格外的小心,往往操作不當,導致iterator失效,後果就是程序奔潰。

    1. 對於vector,erase會返回下一個iterator。所以一般採用的方法是:

     因爲在使用erase的時候,刪除元素前面的iterator有效,但是後面的iterator就不可預知了。

#include <iostream>
#include <vector>
#include <iterator>
using namespace std;

void displayAllDate(vector<int>& inputDate)
{
    vector<int>::iterator itor = inputDate.begin();
    cout << endl;
    while (itor != inputDate.end())
    {
        cout << *itor << " ";
        ++itor;
    }
}

int main()
{
    vector<int> inputDate;
    for (int i = 0; i < 10; i++)
    {
        inputDate.push_back(i);
    }
    
    vector<int>::iterator iter = inputDate.begin();
    while (iter != inputDate.end())
    {
        if (0 == (*iter)%2)
        {
            iter = inputDate.erase(iter);
        }
        else
        {
            ++iter;
        }
    }

    displayAllDate(inputDate);
    return 0;
}
    運行結果:

    

    2. 對於map,刪除erase之後,只會影響到當前的iterator,因此我們一般推薦以下方法:

#include <iostream>
#include <map>
#include <iterator>
using namespace std;

void displayAllDate(map<int, int>& inputDate)
{
    map<int, int>::iterator itor = inputDate.begin();
    cout << endl;
    while (itor != inputDate.end())
    {
        cout << itor->second << " ";
        ++itor;
    }
}

int main()
{
    map<int, int> inputDate;
    for (int i = 0; i < 10; i++)
    {
        inputDate[i] = i + 10;
    }

    map<int, int>::iterator iter = inputDate.begin();
    while (iter != inputDate.end())
    {
        if (0 == (iter->second) % 2)
        {
            inputDate.erase(iter++);
        }
        else
        {
            ++iter;
        }
    }

    displayAllDate(inputDate);
    return 0;
}
    運行結果:

    

   但是要注意的一點,map的erase操作在window下面也可以用vector的方法實現,但是在linux下是編譯不過的。所以推薦使用上面的方法。

#include <iostream>
#include <map>
#include <iterator>
using namespace std;

void displayAllDate(map<int, int>& inputDate)
{
    map<int, int>::iterator itor = inputDate.begin();
    cout << endl;
    while (itor != inputDate.end())
    {
        cout << itor->second << " ";
        ++itor;
    }
}

int main()
{
    map<int, int> inputDate;
    for (int i = 0; i < 10; i++)
    {
        inputDate[i] = i + 10;
    }

    map<int, int>::iterator iter = inputDate.begin();
    while (iter != inputDate.end())
    {
        if (0 == (iter->second) % 2)
        {
            iter = inputDate.erase(iter);
        }
        else
        {
            ++iter;
        }
    }

    displayAllDate(inputDate);
    return 0;
}
    運行結果是:

    

    參考:

    http://www.cnblogs.com/dabaopku/p/3912662.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章