C++Primer 第四版 习题9.27的答案问题

最近在啃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;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值