/** * 功能:定制操作 * 时间:2014年6月19日07:32:03 * 作者:cutter_point */ #include<iostream> #include<vector> #include<string> #include<numeric> #include<algorithm> using namespace std; void elimDups(vector<string> &words) { //按字典顺序排列 sort(words.begin(), words.end()); //unique重排输入范围,使每个单词出现一次 //排列在范围的前部,返回不重复区域之后一个位置的迭代器 auto end_unique=unique(words.begin(), words.end()); //使用向量操作erase删除重复单词 words.erase(end_unique, words.end()); } //如果ctr的值大于1,返回word的复数形式 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); //将words按字典顺序排列,删除重复单词 //按长度排序,长度相同的单词维持字典序 stable_sort(words.begin(), words.end(), [](const string &a, const string &b){return a.size()<b.size();}); //获取一个迭代器,指向第一个满足size()>=sz的元素 auto wc=find_if(words.begin(), words.end(), [sz](const string &a){return a.size()>=sz;}); //计算满足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<string> words={"fox","jumps","over","quick","red","red","slow","the","the","turtle"}; size_t v1 = 4; biggies(words, v1); return 0; }
/** * 功能:编写一个lambda,接受两个int,返回他们的和 * 时间:2014年6月19日08:10:08 * 作者:cutter_point */ #include<iostream> #include<algorithm> #include<numeric> using namespace std; void demo_14() { int a=42; int b=38; auto c1=[&a,&b]{return a+b;}; cout<<" a+b= "<<c1()<<endl; } void demo_15() { size_t a=38; int c=8; auto d15=[&a](const int &b){return a+b;}; cout<<" a+b= "<<d15(c)<<endl; a=42; auto j=d15(c); cout<<" a+b= "<<d15(c)<<" j= "<<j<<endl; } int main() { demo_14(); demo_15(); return 0; }
void biggies(vector<string> &words, vector<string>::size_type sz, ostream &os=cout, char c=' ') { elimDups(words); //将words按字典顺序排列,删除重复单词 //按长度排序,长度相同的单词维持字典序 stable_sort(words.begin(), words.end(), [](const string &a, const string &b){return a.size()<b.size();}); //获取一个迭代器,指向第一个满足size()>=sz的元素 auto wc=find_if(words.begin(), words.end(), [sz](const string &a){return a.size()>=sz;}); //计算满足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; */ for_each(words.begin(), words.end(), [&os, c](const string &s){os<<s<<c;}); }
【足迹C++primer】32、定制操作_2,布布扣,bubuko.com
原文地址:http://blog.csdn.net/cutter_point/article/details/32301839