void fillVector(vector<int>& v)
{
// A local static variable.
static int nextValue = 1;
// The lambda expression that appears in the following call to
// the generate function modifies and uses the local static
// variable nextValue.
generate(v.begin(), v.end(), [] { return nextValue++; });
//WARNING: this is not thread-safe and is shown for illustration only
}
四、应用Lambda的比较函数的编写
为什么要补充这一部分呢?因为我们在写程序的时候,往往最常用到lambda的地方就是数组的sort。
首先,我们知道std::sort默认是接受2个参数的,表示需要排序的序列的开始和结尾。对于一些复杂的数据类型,我们可以给它添加一个用来比较的函数 operator <。但更多的是通过给sort添加第三个参数来实现。而这个参数就是一个比较器。
sort默认使用<比较符来进行比较,排序的结果是升序。我们写的比较函数的功能就是代替<。记住这个特点,就不会在编写比较函数的时候理不清思路。
这里举一个小例子,给一组点坐标,按欧氏距离排序:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector< pair<int, int> > arr;
arr.push_back(make_pair(1, 4));
arr.push_back(make_pair(2, 3));
arr.push_back(make_pair(5, 7));
arr.push_back(make_pair(6, 2));
sort(arr.begin(), arr.end(),
[](pair<int, int> left, pair<int, int> right) {
int d1 = left.first * left.first + left.second * left.second;
int d2 = right.first * right.first + right.second * right.second;
return d1 < d2;
});
for (auto &p: arr) {
cout << "(" << p.first << ", " << p.second << ")" << endl;
}
return 0;
}
输出结果:
(2, 3)
(1, 4)
(6, 2)
(5, 7)
唯一需要注意的是,我们的比较函数取代的是<。
PS:
lambda 怎么传递ref参数
ambda 传递ref参数有个语法bug,必须要显式书写参数类型。
//如
delegate bool FuncType(ref int num);
FuncType func1;
func1 = num => true; //错
func1 = (ref num) => true;//错
func1 = (ref int num) => true;//ok
//并且,当一个参数书写类型,其他参数也要书写,总之很烦。
以上所述是小编给大家介绍的C++ 中的Lambda表达式写法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对ASPKU网站的支持!
注:相关教程知识阅读请移步到C++教程频道。










