【足迹C++primer】32、定制操作_1
定制操作
向算法传递函数
谓词
bool isShorter(const string &s1, const string &s2) { return s1.size()<s2.size(); } int main() { //按长度由短至长排序words sort(words.begin(), words.end(), isShorter); }
这个words里面是一个string类型的数组,这个调用会是将words重排,所有长度为3的单词排在长度为4的前面,然后是长度为5的单词。
排序算法
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;
lambda表达式
计算满足size>=sz的元素的数目
介绍lambda
//是不是有点不一样,这里定义了可调用对象f,它不接受参数,返回42 auto f=[] {return 42;};
//看哥调用它 cout<<f()<<endl;
这里如果lambda的函数体包含任何单一return语句之外的内容、且为指定返回类型,则返回void类型
向lambda传递参数,使用捕获列表
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! ";}); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。