[C++11] lambda表达式

来源:互联网 发布:地板 知乎 编辑:程序博客网 时间:2024/06/06 17:53

可调用对象有四种:函数、函数指针、重载了函数调用运算符的类和lambda表达式。

lambda表达式表示一个可调用的代码单元,可以理解为未命名的内联函数。它具有返回类型,参数列表和函数体。lambda可以定义在函数内部。其形式如下:

[capture list](parameter list) -> return type { function body }
capture list 捕获列表是一个lambda所在函数中定义的局部变量的列表,返回值,参数列表和函数体与普通函数一样。但是lambda必须使用尾置返回类指定返回类型。

int _tmain(int argc, _TCHAR* argv[]){auto f = [] { return 42; };cout << f() << endl;return 0;}

向lambda传递参数

与调用函数类似,调用lambda时给定的实参被用来初始化lambda的形参但是lambda不支持默认参数。下面就是与上一篇中的isShorter函数的lambda:

[](const string &a, const string &b){ return a.size() < b.size();}
在stable_sort中调用lambda:

int _tmain(int argc, _TCHAR* argv[]){// 创建并初始化字符串向量vector<string> words{ "aaa", "c", "eeee", "b", "cccc", "c" };// 移除重复单词并按字典序排序elimDumps(words);// 将向量按字符串大小排序,使用稳定排序算法保持相同长度的单词按字典序排列stable_sort(words.begin(), words.end(), [](const string &a, const string &b){ return a.size() < b.size();});for (auto &s : words){cout << s << endl;}return 0;}

使用捕获列表

假设要解决的问题是计算一组字符串向量中,单词长度大于给定值的单词的数量。

假设要使用find_if来找出字符串数组中字符串大小大于指定长度的字符串,我们可以为find_if算法提供一个实现这个比较的lambda,并使用捕获列表为lambda提供一个局部变量sz,lambda将会捕获sz,其函数体会将string的大小和捕获的sz的值进行比较:

[sz](const string &a){return a.size() >= sz;}
在find_if中使用lambda:

auto wc = find_if(words.begin(), words.end(), [sz](const string &a){return a.size() >= sz;});
find_if返回的迭代器指向第一个长度不小于给定参数sz的元素,如果这样的元素不存在,则返回words.end()的一个拷贝。
void biggiest(vector<string> &words, vector<string>::size_type sz){elimDumps(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_plura(count, "word", "s")<< " of length " << sz << " or longer" << endl;// 打印长度大于等于给定值的单词,每个单词后面接一个空格for_each(wc, words.end(),[](const string &s) { cout << s << " ";});cout << endl;}
程序执行结果如下:







0 0
原创粉丝点击