bool isShorter(const string &s1, const string &s2) { return s1.size()<s2.size(); } int main() { //按长度由短至长排序words sort(words.begin(), words.end(), isShorter); }
vector<string> words={"fox","jumps","over","quick","red","red","slow","the","the","turtle"}; //按长度由短至长排序words sort(words.begin(), words.end(), isShorter); elimDups(words); //将words按字典序重排,并消除重复单词 //按长度重排,长度一样按字典 stable_sort(words.begin(), words.end(), isShorter); for(const auto &s : words) //无需拷贝字符串 cout<<s<<" "; //打印每个元素 cout<<endl;
//调用算法进行排序打印长度大于5的元素 auto it=partition(words.begin(), words.end(), isLong); //返回的是使谓词为true的最后一个迭代器 cout<<"输出长度大于等于5的字符!!"<<endl; for(vector<string>::iterator st=words.begin() ; st != it ; ++st) cout<<*st<<" "; cout<<endl;
//是不是有点不一样,这里定义了可调用对象f,它不接受参数,返回42 auto f=[] {return 42;};
//看哥调用它 cout<<f()<<endl;
stable_sort(words.begin(), words.end(), [] (const string &a, const string &b) {return a.size()<b.size();})
void fcn1() { vector<string> words={"fox","jumps","over","quick","red","red","slow","the","the","turtle"}; size_t v1 = 42; //获取一个迭代器,指向第一个满足size()>=v1的元素 auto wc=find_if(words.begin(), words.end(), [v1](const string &a){return a.size()>=v1;}); }
void fcn2() { vector<string> words={"fox","jumps","over","quick","red","red","slow","the","the","turtle"}; size_t v1 = 42; //获取一个迭代器,指向第一个满足size()>=v1的元素 auto wc=find_if(words.begin(), words.end(), [v1](const string &a){return a.size()>=v1;}); //计算满足size>=sz的元素的数目 auto count=words.end()-wc; cout<<count<<" "<<make_plural(count, "word", "s") <<" of length "<<v1<<" or longer "<<endl; //for_each算法 for_each(wc, words.end(),[](const string &s){cout<<s<<" yeah! ";}); }
【足迹C++primer】32、定制操作_1,布布扣,bubuko.com
原文地址:http://blog.csdn.net/cutter_point/article/details/32066151