erase 函数

场景:erase()函数对器皿干了啥

erase()函数对容器干了啥?
#include <iostream>
#include <list>

using namespace std;

int main()
{
    int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};
    list<int> ilist (ia, ia+11);

    int nLen = ilist.size();

    list<int>::iterator it = ilist.begin();

    for(int index=0; index < nLen; index++)
    {   
        if((index+1)%2 != 0)
        {
            ilist.erase(it);
        }
        it++;
    }
    return 0;
}



预测一下,结果会怎样。

------解决方案--------------------
erase之后,迭代器失效,结果大概会报错
------解决方案--------------------
        if((index+1)%2 != 0)
        {
            it= ilist.erase(it);
        }
        else
            it++;
这样应该就行了,it本质就是指向一个节点的指针,你把节点删了,it就已经没意义,再it++,肯定就出错了。
幸好,erase会返回删除元素的下一个元素的迭代器。
------解决方案--------------------
很显示,程序要崩掉了。
可以这么改
for(int index=0; (index < nLen) &&(it != ilist.end()); index++)
{   
if((index+1)%2 != 0)
{
it = ilist.erase(it);
}
it++;
}