vector中使用erase删除元素

很容易受数组的影响,写出如下代码:
std::vecotr<int>::iterator it = vc.begin();
for( ; it != vc.end(); it++ )
{
    if( ***** )    vc.erase(it);
}

原因是vector中在删除一个元素后,迭代器会自动指向下一个元素。所以,上面的代码很可能导致迭代器越界。
《The C++ Standard Library》中解释:

c.erase(pos) Removes the element at iterator position pos and returns the position of the next element

所以,正确做法应该是:
for( ; it != vc.end(); )
{
    if( ***** )
    {
        vc.erase(it);
     }
    else
    {
        it++;
    }
}

问题又来了,上面的代码在C++ Builder 6.0 、Mingw32 2.95下编译运行完全正常,但vc下面同样会出错(Visual Studio 2008),在erase后,it失效,并不是指向vector的下一个元素,it成了一个“野指针”。

例子:

#include "iostream"
#include "vector"

using namespace std;

int   main()
{
    vector<int>   arr;
    arr.push_back(6);
    arr.push_back(8);
    arr.push_back(3);
    arr.push_back(8);

    for(vector<int>::iterator it=arr.begin(); it!=arr.end(); )
    {
        if(* it == 8)
        {
            it = arr.erase(it);
        }
        else
        {
            ++it;
        }
    }

    cout << "After remove 8:\n";

    for(vector<int>::iterator it = arr.begin(); it < arr.end(); ++it)
    {
        cout << * it << " ";
    }
    cout << endl;

}

你可能感兴趣的:(vector中使用erase删除元素)