C++ primer 第五版 中文版 练习 10.20 个人code

本文提供C++ Primer第五版中文版习题10.20的答案,利用标准库中的count_if函数重写统计单词长度超过6的部分。通过具体代码实现展示了如何运用此算法简化程序。

C++ primer 第五版 中文版 练习 10.20

题目:标准库定义了一个名为 count_if 的算法。类似find_if,此函数接受一对迭代器,表示一个输入范围,还接受一个谓词,
会对输入范围中每个元素执行。count_if返回一个计数值,表示谓词有多少次为真。使用count_if重写我们的程序中统计有多少单词长度超过6的部分。


答:

/*
标准库定义了一个名为 count_if 的算法。类似find_if,此函数接受一对迭代器,表示一个输入范围,还接受一个谓词,
会对输入范围中每个元素执行。count_if返回一个计数值,表示谓词有多少次为真。使用count_if重写我们的程序中统计有多少单词长度超过6的部分。
*/

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

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());
	cout << "vector用sort重排后的元素内容为:";
	for (auto a : words)
		cout << a << " ";
	cout << endl;

	auto end_unique = unique(words.begin(), words.end());
	cout << "vector用unique重排后的元素内容为:";
	for (auto a : words)
		cout << a << " ";
	cout << endl;

	words.erase(end_unique, words.end());
	cout << "vector中删除重复元素后的内容为:";
	for (auto a : words)
		cout << a << " ";
	cout << endl;

}

string make_plural(size_t ctr, const string &word, const string &ending)
{
	return (ctr > 1) ? word + ending : word;
}
void biggies(vector<string> &words, vector<string>::size_type sz)
{
	elimDups(words);
	stable_sort(words.begin(), words.end(), [](const string &a, const string &b){return a.size() < b.size(); });

	auto cnt = count_if(words.begin(), words.end(), [sz](const string &s){return s.size()>=sz; });

	cout << cnt << " " << make_plural(cnt, "word", "s") << " of length " << sz << " or longer" << endl;


	cout << endl;


}
int main()
{
	vector<string> svect = { "the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle" };

	biggies(svect, 6);

	return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值