c++ primer 第五版习题答案9.28

本文介绍了一个实用的C++函数,该函数用于在forward_list中查找指定字符串并插入另一个字符串。通过具体示例展示了如何使用此函数进行链表操作。

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

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

#include<iostream>
#include<vector>
#include<string>
#include<deque>
#include<list>
#include<forward_list>
using namespace std;

void my_insert(forward_list<string> &f, const string &s1,const string &s2)
{
	auto prev = f.before_begin();
	auto curr = f.begin();
	while (curr != f.end())
	{
		if (*curr == s1)
		{	f.insert_after(curr, s2);
			return;
		}
		else
		{
			prev = curr;
			++curr;
		}
	}
	f.insert_after(prev,s2);
	return;
}//这里必须有return,Google很好用!

int main()
{
	forward_list<string> my_vector{ "chen", "xun", "is", "an","student" };
	my_insert(my_vector, "an", "excellent");
	my_insert(my_vector, "student", ",oh yeah!");
	for (auto &a : my_vector)
		cout << a << ' ';
	cout << endl;
	return 0;
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值