勤能补拙,Expter

成都游戏Coder,记录游戏开发过程的笔记和心得!

一个STL的笔试改错题

# include <iostream>
# include 
<list>
using namespace std;

int main()
{
    
int i;
    list
<int> list1;
    
for(i = 0; i < 8; i++)
       list1.push_back(i);

    
for(list<int>::iterator  it= list1.begin(); it != list1.end(); it++)
    
{
             
if (*it %2 )
        list1.erase(it);
    }


    
return 0;
}
又定义可以知道list1删除it后,后面的节点的断了。。

因为erase方法是返回的删除的节点的下一个节点的地址。。所有改错后的代码
# include <iostream>
# include 
<list>
using namespace std;

int main()
{
    
int i;
    list
<int> list1;
    
for(i = 0; i < 8; i++)
       list1.push_back(i);

    
for(list<int>::iterator  it= list1.begin(); it != list1.end(); it++)
    
{
        
//cout << *it <<endl;
         if (*it %2 )
            it 
=list1.erase(it);
    }

    
for(it= list1.begin(); it != list1.end(); it++)
    
{
        cout 
<< *it <<endl;
    }

    
return 0;
}

posted on 2008-10-20 20:35 expter 阅读(1289) 评论(4)  编辑 收藏 引用

评论

# re: 一个STL的笔试改错题 2008-10-21 10:45 唐鹏

因为程序1
在用户删除一个节点后,被删除的节点后面的就成为了单独的链表  回复  更多评论   

# re: 一个STL的笔试改错题 2008-10-21 23:53 faicker

因为erase方法是返回的删除的节点的下一个节点的地址...
------------------------------------------------
再it++会漏掉节点的~
这个题目里面没问题~  回复  更多评论   

# re: 一个STL的笔试改错题 2008-12-22 23:39 酒明远

你上面的程序好像有点问题呀,应该是这样的吧
# include <iostream>
# include <list>
using namespace std;

int main()
{
int i;
list<int> list1;
for(i = 0; i < 8; i++)
list1.push_back(i);

for(list<int>::iterator it= list1.begin(); it != list1.end(); )
{
if (*it %2 )
it=list1.erase(it);
else
it++;
}

for(list<int>::iterator it= list1.begin(); it != list1.end(); it++)
cout<<*it<<endl;

return 0;


}  回复  更多评论   

# re:我用向量试了一下 2009-01-28 17:48 http://www.ok2002.com/

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

void main()
{
int n[]={1,2,3,4,5,6,7,8,9,0};
vector<int>v(n,n+sizeof(n)/4);
vector<int>::iterator i;

for(i=v.begin();i!=v.end();++i)
cout<<*i<<" ";
cout<<endl;

for(i=v.begin();i!=v.end();)
{
if(*i%2==0)
i=v.erase(i);//erase返回被删除的节点的下一个节点的地址
else
++i;
}

for(i=v.begin();i!=v.end();++i)
cout<<*i<<" ";
cout<<endl;
}

/*--运行结果:
1 2 3 4 5 6 7 8 9 0
1 3 5 7 9
Press any key to continue
--*/
  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理