C++primer 习题9。25答案错误,正确答案如下

#include<iostream>

#include<vector>

#include<list>

using namespace std;

int main()

{

int ia[]={0,1,1,2,3,5,8,13,21,55,89};

vector<int> ivec(ia,ia+sizeof(ia)/sizeof(int));

list<int> ilist(ia,ia+sizeof(ia)/sizeof(*ia));

 

 

for(vector<int>::iterator iter1 = ivec.begin();iter1 != ivec.end();)

{

       if(*iter1 % 2 == 0)

  {

 

  iter1 = ivec.erase(iter1);   //erase()函数返回一个迭代器,指向删除元素后面的元素,因此,此事不需要 ++iter1;

 

  }

  else

  {

  ++iter1;   //如果没有删除元素,则正常 ++iter2,指向下一个元素进行判断

  }

 

  

}

 

for(list<int>::iterator iter2=ilist.begin();iter2 != ilist.end();)

 

{

       if(*iter2 % 2 != 0)

  {

  

  iter2 = ilist.erase(iter2);

  }

  else

  {

  ++iter2;

  }

 

  

  

}

 

 

vector<int>::iterator iter1 = ivec.begin();

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

 

 

    cout<<"奇数:"<<endl;

for(;iter1!=ivec.end();++iter1)

{

cout<<*iter1<<endl;

}

 

cout<<"偶数:"<<endl;

    for(;iter2!=ilist.end();++iter2)

{

cout<<*iter2<<endl;

}

 

   system("pause");

return 0;

}

你可能感兴趣的:(C++,iterator,System)