erase()函数对容器干了啥?

生活简单到无聊 2013-08-30 04:45:14
#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;
}



预测一下,结果会怎样。
...全文
92 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2013-08-30
  • 打赏
  • 举报
回复
计算机组成原理→DOS命令→汇编语言→C语言(不包括C++)、代码书写规范→数据结构、编译原理、操作系统→计算机网络、数据库原理、正则表达式→其它语言(包括C++)、架构…… 对学习编程者的忠告: 眼过千遍不如手过一遍! 书看千行不如手敲一行! 手敲千行不如单步一行! 单步源代码千行不如单步对应汇编一行! 单步类的实例“构造”或“复制”或“作为函数参数”或“作为函数返回值返回”或“参加各种运算”或“退出作用域”的语句对应的汇编代码几步后,就会来到该类的“构造函数”或“复制构造函数”或“运算符重载”或“析构函数”对应的C/C++源代码处。 VC调试时按Alt+8、Alt+7、Alt+6和Alt+5,打开汇编窗口、堆栈窗口、内存窗口和寄存器窗口看每句C对应的汇编、单步执行并观察相应堆栈、内存和寄存器变化,这样过一遍不就啥都明白了吗。 对VC来说,所谓‘调试时’就是编译连接通过以后,按F10或F11键单步执行一步以后的时候,或者在某行按F9设了断点后按F5执行停在该断点处的时候。 (Turbo C或Borland C用Turbo Debugger调试,Linux或Unix下用GDB调试时,看每句C对应的汇编并单步执行观察相应内存和寄存器变化。)
海的神话 2013-08-30
  • 打赏
  • 举报
回复
很显示,程序要崩掉了。 可以这么改 for(int index=0; (index < nLen) &&(it != ilist.end()); index++) { if((index+1)%2 != 0) { it = ilist.erase(it); } it++; }
woshinia 2013-08-30
  • 打赏
  • 举报
回复
if((index+1)%2 != 0) { it= ilist.erase(it); } else it++; 这样应该就行了,it本质就是指向一个节点的指针,你把节点删了,it就已经没意义,再it++,肯定就出错了。 幸好,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();
    list<int>::iterator it2 = it;
    for(int index=0; index < nLen; index++)
    {
        list<int>::iterator it3 = (++it2);
        cout<<(*it3)<<endl;

        if((index+1)%2 != 0)
        {
            ilist.erase(it);
        }
        it = it3;
        it2 = it3;


        list<int>::iterator itmp= ilist.begin();
        for(;itmp !=ilist.end(); itmp++)
        {
            cout<<(*itmp)<<" ";
        }
        cout<<endl;

    }

    it = ilist.begin();

    for(;it !=ilist.end(); it++)
    {
        cout<<(*it)<<" ";
    }
    return 0;
}
这样就对了,但是具体不知道第一次代码问题的原因。
nice_cxf 2013-08-30
  • 打赏
  • 举报
回复
erase之后,迭代器失效,结果大概会报错
onlyhuiyi 2013-08-30
  • 打赏
  • 举报
回复
关注一下。

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧