一. 书写形式
[ capture clause ] (parameters) -> return-type { definition of method }
[ 捕获 ] ( 参数列表 ) -> 返回类型 { 函数定义 }
return-type返回值一般可以推导出来, 可以不用写, 所以可以简化为
[ capture clause ] (parameters) { definition of method }
但是在一些复杂的情况下, 比如条件语句
这种, return-type是不能省略的
几个用例
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;void print_vector(vector<int> v)
{for_each(v.begin(), v.end(), [](int i) {cout << i << " ";});cout << endl;
}int main() {vector<int> v{ 4, 1, 3, 5, 2, 3, 1, 7 };print_vector(v);// 首个比4大的数字vector<int>::iterator p = find_if(v.begin(), v.end(), [](int i) {return i > 4;});cout << "first number greater than 4 is " << *p << endl;// 排序sort(v.begin(), v.end(), [](const int& a, const int& b) {return a > b;});print_vector(v);// 大于等于5的数字的个数int bigger_than_5_number = count_if(v.begin(), v.end(), [](int a) {return a >= 5;});cout << "the number of elements greater than or equal 5 is: " << bigger_than_5_number << endl;// 去重vector<int>::iterator p2 = unique(v.begin(), v.end(), [](int a, int b) {return a == b;});v.resize(distance(v.begin(), p2));print_vector(v);int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };// 阶乘int res = accumulate(arr, arr + 10, 1, [](int a, int b) {return a * b;});// 平方auto square = [](int i) {return i * i;};cout << "square of 5 is : " << square(5) << endl;
}
执行结果
二. 详解捕获
lambda表达式还能够从闭包中获取数据, 就是[]
中声明的
[a]: 不写&
和=
的话, 默认值捕获
有三种方式:
[&] : 通过引用捕获所有外部变量
[=] : 通过值捕获所有外部变量
[a, &b] : a通过值捕获, b通过引用捕获
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;int main() {vector<int> v1 = { 3, 1, 7, 9 };vector<int> v2 = { 10, 2, 7, 16, 9 };auto push_number = [&](int a) {v1.push_back(a);v2.push_back(a);};push_number(20);auto print_v1 = [v1]() {for (auto p = v1.begin(); p != v1.end(); p++)cout << *p << " ";cout << endl;};print_v1();int N = 5;// 首个比N大的数vector<int>::iterator p = find_if(v1.begin(), v1.end(), [N](int i) {return i > N;});cout << "first number greater than 5 is " << *p << endl;// 大于等于5的数int count_n = count_if(v1.begin(), v1.end(), [=](int i) {return i >= N;});cout << "the number of elements greater than or equal 5 is " << count_n << endl;
}
执行结果