第九章 9.3.4节练习 & 9.3.5节练习

本文提供了C++标准模板库中forward_list的两个实用示例:一是删除链表中的所有奇数元素;二是查找指定字符串并插入新元素。此外,还探讨了vector在调整大小时的行为。

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

练习9.27:

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

解答:

这段程序在本节已经给出来了,不过,forward_list是单向链表,比较特殊,所以这段程序还是值得花点时间看看的。

#include <iostream>
#include <forward_list>

using namespace std;

int main(){
	forward_list<int> flst{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	auto prev = flst.before_begin();
	auto curr = flst.begin();
	while (curr != flst.end()){
		if (*curr % 2){
			curr = flst.erase_after(prev);
		}
		else{
			prev = curr;
			++curr;
		}
	}

	for (auto i : flst){
		cout << i << " ";
	}
	cout << endl;
}

练习9.28:

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

解答:

#include <iostream>
#include <forward_list>
#include <string>
using namespace std;

void myFunc(forward_list<string>& flst, string str1, string str2){
	auto perv = flst.before_begin();
	auto curr = flst.begin();
	while (curr != flst.end()){
		if (*curr == str1){
			flst.insert_after(curr, str2);
			return;
		}
		perv = curr;
		++curr;
	}
	flst.insert_after(perv, str2);
}

int main(){
	forward_list<string> flist{ "apple", "melon", "pear", "banana" };
	myFunc(flist, "pear", "watermelon");
	for (auto i : flist){
		cout << i << " ";
	}
	cout << endl;

	myFunc(flist, "house", "pineapple");
	for (auto i : flist){
		cout << i << " ";
	}
	cout << endl;
}


练习9.29:

假定vec包含25个元素,那么vec.resize(100)会做什么?如果接下来调用vec.resize(10)会做什么?

解答:

和314页list描述相似的处理方式。

#include <iostream>
#include <vector>

using namespace std;

int main(){
	vector<int> vec(25, 99);
	cout << "Original vec vessel elements" << endl;
	for (auto i : vec){
		cout << i << " ";
	}
	cout << endl;

	vec.resize(100);
	cout << "Resize the vessel to 100, the elements" << endl;
	for (auto i : vec){
		cout << i << " ";
	}
	cout << endl;

	vec.resize(25);
	cout << "Resize the vessel to 25, the elements" << endl;
	for (auto i : vec){
		cout << i << " ";
	}
	cout << endl;

}


练习9.30:

接受单个参数的resize版本对元素类型有什么限制(如果有的话)?

解答:

限制能想到的只有一个。

【引用】如果容器保存对的是类类型元素,且resize想容器添加新元素,则我们必须提供初始值,或者元素类型必须提供一个默认构造函数。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值