C++ primer 第五版 中文版 9.3.4 节练习

本文详细解答了C++ Primer第五版中文版第九章的两道练习题,包括删除forward_list<int>中的奇数元素和在forward_list<string>中查找并插入字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



C++ primer 第五版 中文版 9.3.4 节练习


练习 9.27:编写程序,查找并删除forward_list<int>中的奇数元素。

答:

/*
编写程序,查找并删除forward_list<int>中的奇数元素。
*/

#include <iostream>
#include <forward_list>

using std::cout;
using std::endl;
using std::forward_list;

int main()
{
	forward_list<int> flist{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20 };
	
	cout << "删除奇数元素前flist中的元素内容为:";
	for (const auto &a : flist)
		cout << a << " ";
	cout << endl;
	auto prev = flist.before_begin();
	auto curr = flist.begin();

	while (curr != flist.end())
	{
		if (*curr % 2)
		{
			curr = flist.erase_after(prev);
		}
		else
		{
			prev = curr;
			++curr;
		}
	}

	cout << "删除奇数元素后flist中的元素内容为:";
	for (const auto &a : flist)
		cout << a << " ";
	cout << endl;

	return 0;
}

执行结果:


练习 9.28:编写函数,接受一个forward_list<string> 和两个 string 共三个参数。函数应在链表中查找第一个string,并将第二个string插入到紧接着第一个string之后的位置。若第一个string未在链表中,刚将第二个string 插入到链表末尾。

答:

/*
编写函数,接受一个forward_list<string> 和两个 string 共三个参数。
函数应在链表中查找第一个string,并将第二个string插入到紧接着第一个string之后的位置。
若第一个string未在链表中,刚将第二个string 插入到链表末尾。
*/

#include <iostream>
#include <forward_list>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::forward_list;
using std::string;

//在单向链表flist中查找findword,并将 insertword插入到找到的findword之后的位置。若findword未在链表中,则将insertword 插入到链表末尾。
void find_or_insert(forward_list<string> &flist, const string &findword, const string &insertword)
{
	auto tmpiter = flist.before_begin();
	auto curriter = flist.begin();
	bool flag = false;
	while (curriter != flist.end())
	{
		if (*curriter == findword)
		{
			flag = true;
			curriter = flist.insert_after(curriter, insertword);
		}
		else
		{	
			tmpiter = curriter;
			++curriter;
		}
	}
	if (!flag)
		flist.insert_after(tmpiter, insertword);	
}

int main()
{
	forward_list<string> strflist = { "Hello", "C++", "I", "got", "you" ,"Hello","Primer"};

	cout << "list<string>容器内的元素为:";
	for (const auto &a : strflist)
		cout << a << " ";
	cout << endl;

	string findkeyword, insertkeyword;

	cout << "请输入要查找的关键词和要插入的关键词:";

	cin >> findkeyword >> insertkeyword;

	find_or_insert(strflist, findkeyword, insertkeyword);

	cout << "插入关键词后list<string>容器内的元素为:";
	for (const auto &a : strflist)
		cout << a << " ";
	cout << endl;

	return 0;

}


执行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值