#include <iostream>
using namespace std;
int main()
{
int i = 1024;
auto func = [] { cout << i; };
func();
} // 结果报错,因为未指定默认捕获模式
正确的如下:
#include <iostream>
using namespace std;
int main()
{
int i = 1024;
auto func = [=]{ // [=] 表明将外部的所有变量拷贝一份到该Lambda函数内部
cout << i;
};
func();
}
2、引用捕获
#include <iostream>
using namespace std;
int main()
{
int i = 1024;
cout << &i << endl;
auto fun1 = [&]{
cout << &i << endl;
};
fun1();
}
3、复制并引用捕获
#include <iostream>
using namespace std;
int main()
{
int i = 1024, j = 2048;
cout << "i:" << &i << endl;
cout << "j:" << &j << endl;
auto fun1 = [=, &i]{ // 默认拷贝外部所有变量,但引用变量 i
cout << "i:" << &i << endl;
cout << "j:" << &j << endl;
};
fun1();
}
4、指定引用或复制
#include <iostream>
using namespace std;
int main()
{
int i = 1024, j = 2048;
cout << "outside i value:" << i << " addr:" << &i << endl;
auto fun1 = [i]{
cout << "inside i value:" << i << " addr:" << &i << endl;
// cout << j << endl; // j 未捕获
};
fun1();
}
5、捕获this指针
#include <iostream>
using namespace std;
class test
{
public:
void hello() {
cout << "test hello!n";
};
void lambda() {
auto fun = [this]{ // 捕获了 this 指针
this->hello(); // 这里 this 调用的就是 class test 的对象了
};
fun();
}
};
int main()
{
test t;
t.lambda();
}
// 指明返回类型
auto add = [](int a, int b) -> int { return a + b; };
// 自动推断返回类型
auto multiply = [](int a, int b) { return a * b; };
int sum = add(2, 5); // 输出:7
int product = multiply(2, 5); // 输出:10
1882C++ 函数
两个实际应用到lambda表达式的代码。
std::vector<int> v = { 1, 2, 3, 4, 5, 6 };
int even_count = 0;
for_each(v.begin(), v.end(), [&even_count](int val){
if(!(val & 1)){
++ even_count;
}
});
std::cout << "The number of even is " << even_count << std::endl;
int count = std::count_if( coll.begin(), coll.end(), [](int x){ return x > 10; });
int count = std::count_if( coll.begin(), coll.end(), [](int x){ return x < 10; });
int count = std::count_if( coll.begin(), coll.end(), [](int x){ return x > 5 && x<10; });
#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
int a, b, c, d, m, n,z;
a = 10;
b = 20;
c = 30;
d = 40;
m = a > b ? a : b;
n = c > d ? c : d;
z = m > n ? m : n;
cout<<"最大值为:"<<z<<endl;
return 0;
}
1884C++ 函数
Lambda函数很简洁,但变化较多。
1、什么也不捕获,或者是故意不用 Lambda 函数外部的变量
正确的如下:
2、引用捕获
3、复制并引用捕获
4、指定引用或复制
5、捕获this指针
1883C++ 函数
定义一个可以输出字符串的lambda表达式,表达式一般都是从方括号[]开始,然后结束于花括号{},花括号里面就像定义函数那样,包含了lamdba表达式体:
如果需要参数,那么就要像函数那样,放在圆括号里面,如果有返回值,返回类型要放在->后面,即拖尾返回类型,当然你也可以忽略返回类型,lambda会帮你自动推断出返回类型:
1882C++ 函数
两个实际应用到lambda表达式的代码。
1881C++ 函数
Lambda 函数与表达式
Lambda函数的语法定义如下:
其中:
在 lambda 函数的定义式中,参数列表和返回类型都是可选部分,而捕捉列表和函数体都可能为空,C++ 中最简单的 lambda 函数只需要声明为:
1880C++ 判断
求 a,b,c,d 四个数中的最大数。