第十章 10.2.3节练习 & 10.3.1节练习

本文通过几个具体的练习题解答,介绍了如何使用C++ STL中的容器如vector和set进行数据处理,包括排序、去重等操作,并展示了如何利用算法如unique、sort和partition来高效地管理容器内容。

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

练习10.9:

实现你自己的elimDups。测试你的程序,分别在读取输入后、调用unique后及调用erase后打印vector的内容。

解答:

恩,书上已经实现了一个。就不在去累述了。

如果让我去实现,我感觉unique还是比较麻烦的,我会选用set容器去做除重的工作。


练习10.10:

你认为算法不改变容器大小的原因是什么?

解答:

算法,就是计算方法而已。其本意很明确,只是单纯的做计算,而不去改变参与运算元素个数。

如果,一个算法在计算过程中,参与运算的原始元素个数是动态的,这个算法就应该是不可控的。

不可控的算法对于我们来说,就是无用的算法。

为了保证算法的单纯作用,它是不能改变容器大小的,也就是参与运算的元素个数。


练习10.11:

编写程序,使用stable_sort和isShort将传递给你的elimDups版本的vector排序。打印vector的内容,验证你的程序的正确性。

解答:

#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <iterator>
#include <string>

using namespace std;

bool isShorter(const string &s1, const string &s2){
	return s1.size() < s2.size();
}

void elimDups(vector<string> words){
	sort(words.begin(), words.end(), isShorter);
	auto end_unique = unique(words.begin(), words.end());
	words.erase(end_unique, words.end());

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

int main(){
	vector<string> svec{ "apple", "pear", "hello", "world" };

	elimDups(svec);

	stable_sort(svec.begin(), svec.end(), isShorter);
	for (const auto &s : svec){
		cout << s << " ";
	}
	cout << endl;
}

练习10.12:

编写名为compareIsbn的函数,比较两个Sales_data对象的isbn()成员。使用这个函数排序一个保存Sales_data对象的vector。

解答:

这个其实和上面的代码是一样的,不过是将string替换成Sales_data结构体。将isShorter改写成比较isbn()成员。

这里,懒得去查Sales_data的结构体了,代码就略过吧。


练习10.13:

标准库定义了名为partition的算法,它接受一个谓词,对容器内容进行划分,使得谓词为true的值会排在容器的前半部分,而使谓词为false的值会排在后半部分。

算法返回一个迭代器,指向最后一个是谓词为true的元素之后的位置。编写函数,接受一个string,返回一个bool值,指出string是否有5个或更多字符。使用此函数划分words。打印出长度大于等于5的元素。

解答:

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

bool larger5(const string& str){
	return str.size() >= 5;
}

int main(){
	vector<string> svec{ "a","ac","apple", "pear", "hell", "world", "watermelon", "baidu", "google" };

	vector<string>::iterator bound;
	bound = partition(svec.begin(), svec.end(), larger5);

	for (auto it = svec.cbegin(); it != bound; ++it){
		cout << *it << " ";
	}

	cout << endl;
}

这里的谓词指的就是一个返回bool值的函数,用来做出判断的。

理解这个词,代码马上就能写出来了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值