C++Primers
题目描述:
假设有如下 ia 的定义,将 ia 复制到一个 vector 容器和一个 list 容器中。使用单个迭代器参数版本的 erase 函数将 list 容器中的奇数值元素删除掉,然后将 vector 容器中的偶数值元素删除掉。
int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };
下面是给出的答案:
#include <iostream>
#include <list>
#include <vector>
using namespace std;
int main()
{
int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};
vector<int> nvec(ia, ia + 11);
list<int> nlst(ia, ia + 11);
for (vector<int>::iterator it = nvec.begin(); it != nvec.end();)
{
if (*it % 2)
{
it = nlst.erase(it);
--it; //这里有问题
}
}
for (list<int>::iterator it = nlst.begin(); it != nlst.end(); ++it)
{
if (*it % 2)
{
it = nlst.erase(it);
--it;
}
}
/*
下面两个循环是我自己加的,就是观测下输出值
*/
for (vector<int>::iterator it = nvec.begin(); it != nvec.end(); it++)
{
cout<<"The elements of vector are as follows:"<<endl;
cout<<*it;
}
cout<<endl;
for (list<int>::iterator it = nlst.begin(); it != nlst.end(); it++)
{
cout<<"The elements of vector are as follows:"<<endl;
cout<<*it;
}
cout<<endl;
return 1;
}
[解决办法]
int main()
{
int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};
vector<int> nvec(ia, ia + 11);
list<int> nlst(ia, ia + 11);
for (vector<int>::iterator it = nvec.begin(); it != nvec.end();)
{
if (!(*it % 2))//删偶数
{
it = nvec.erase(it);
// --it; //这里有问题 // erase iterator失效 ,不过--应该没问题
}
else
{
++it;
}
}
for (list<int>::iterator it = nlst.begin(); it != nlst.end(); )
{
if (*it % 2)//删奇数
{
it = nlst.erase(it);
}
else
{
++it;
}
}
for (vector<int>::iterator it = nvec.begin(); it != nvec.end(); it++)
{
cout<<"The elements of vector are as follows:"<<endl;
cout<<*it<<endl;
}
cout<<endl;
for (list<int>::iterator it = nlst.begin(); it != nlst.end(); it++)
{
cout<<"The elements of vector are as follows:"<<endl;
cout<<*it<<endl;
}
cout<<endl;
system("pause");
return 1;
}