练习 10.18:重写 biggies,用 partition 代替 find_if。我们在 10.3.1 节练习 10.13(第 345 页)中介绍了 partition 算法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void elimDups(vector<string> &words)
{
sort(words.begin(), words.end());
auto end_unique = unique(words.begin(), words.end());
words.erase(end_unique, words.end());
}
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 wc = partition(words.begin(), words.end(),
[sz] (const string &a)
{return a.size() >= sz;});
auto count = wc - words.begin();
cout << count << " of length " << sz << " or longer" << endl;
for_each(words.begin(), wc, [] (const string &s) {cout << s << " ";});
cout << endl;
}
int main()
{
vector<string> words = {"the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle"};
biggies(words, 5);
return 0;
}