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

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

题目:重写biggies,用partition代替find_if。我们在10.3.1节练习中介绍了partition算法。

答:

/*
重写biggies,用partition代替find_if。我们在10.3.1节练习中介绍了partition算法。
*/

#include 
#include 
#include 
#include 

using namespace std;

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

void elimDups(vector &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 &words, vector::size_type sz)
{
	elimDups(words);
	stable_sort(words.begin(), words.end(), [](const string &a, const string &b){return a.size() < b.size(); });
	auto wc = partition(words.begin(), words.end(), [sz](const string &a){return a.size() < sz; });
	auto count = words.end() - wc;
	cout << count << " " << make_plural(count, "word", "s") << " of length " << sz << " or longer" << endl;

	for_each(wc, words.end(), [](const string &s){cout << s << " "; });

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

	biggies(svect, 4);

	return 0;

}


你可能感兴趣的:(C++,Primer(第五版),C++,primer,第五版,中文版,lambda,algorithm,泛型算法,partition)