最近在啃C++ primer ,偶然发现习题C++ Primer习题解答 给出的9.27的答案似有不妥。
原答案为:
#include <string>
#include <algorithm>
#include <list>
#include <iostream>
using namespace std;
int main()
{
list<string> slst;
string str;
//读入list对象
string s;
cout<<"Enter some strings(CTRL+Z to end): "<<endl;
while (cin>>str)
slst.push_back(str);
cin.clear();//使流重新处于有效状态
//读入要寻找的值
cout<<"Enter a string that you want to search:"<<endl;
cin>>str;
//处理list对象:删除list对象中与str相同的元素
for (list<string>::iterator iter = slst.begin(); iter != slst.end(); ++iter)
{
if (*iter == str)
{
iter = slst.erase(iter);//Delete element and update iterator
--iter;
}
}
return 0;
}
当要查找并删除的值在第一个位置时,程序就会报错
错误为:
原因分析:
这是因为当要查找的元素位于list<int> slst的第一个位置时,--iter操作将导致iter指向不属于list<int> sls的内存。所以list iterator not decrementable.所以只要在删除元素时判断是不是第一个元素就好了。如果是则删除,但不执行--iter。否则erase 并且--iter。
程序修改之后为:
#include <string>
#include <algorithm>
#include <list>
#include <iostream>
using namespace std;
int main()
{
list<string> slst;
string str;
//读入list对象
string s;
cout<<"Enter some strings(CTRL+Z to end): "<<endl;
while (cin>>str)
slst.push_back(str);
cin.clear();//使流重新处于有效状态
//读入要寻找的值
cout<<"Enter a string that you want to search:"<<endl;
cin>>str;
//处理list对象:删除list对象中与str相同的元素
for (list<string>::iterator iter = slst.begin(); iter != slst.end(); ++iter)
{
if (*iter == str)
{
if (iter == slst.begin())
{
iter = slst.erase(iter);
}
else
{
iter = slst.erase(iter);//Delete element and update iterator
--iter;
}
}
}
return 0;
}