读书人

C++ Primer 习题9.26的有关问题

发布时间: 2012-04-13 13:50:24 作者: rapoo

C++ Primer 习题9.26的问题
题目描述:
假设有如下 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;
}


答案是参考答案给的,调试出现问题,我认为是因为容器vector里的第一个元素是0(偶数),因此就被erase掉了,然而it这时返回的是指向下一个,也就是1的值,然后--it,这时候它前面的元素已经被erase掉了,因此出现了错误,不知道是不是这样。
另外,我不知道怎么修改,我意思是小改动代码,希望大家帮下忙!谢谢!


[解决办法]
去看《effective stl》
[解决办法]

C/C++ code
#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 = 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;} 

读书人网 >C++

热点推荐