一开始的变量捕获不太懂,写一遍就好理解了
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class Test {
public:
void hello() {
cout << "test hello" << endl;
}
void lambda() {
auto fun = [this] { //捕获 this
this->hello();
};
fun();
}
};
int main() {
std::vector<int> numbers = { 1,2,3,4,5 };
std::for_each(numbers.begin(), numbers.end(), [](int x) {
std::cout << "下标x is " << x << " ;" << std::endl;
});
auto sum = [](int a, int b) -> int {
return a + b;
};
std::cout << sum(1, 3) << std::endl;
///捕获外部变量
/**
* 捕获外部变量,2 种方式
* 1. 值捕获: 通过值拷贝外部变量
* 2. 引用捕获: 通过引用捕获外部变量
*/
int x = 10;
auto lambda = [x]() {
std::cout << "x ====" << x << std::endl;
};
lambda();//应该输出 10
auto lambda_ref = [&x]() {
x = 20;
};
lambda_ref();
std::cout << x << std::endl;//输出 20
///经典的 lambda 排序
std::vector<int> my_numbers = { 1,2,77,43,400,5,98,1 };
std::sort(my_numbers.begin(), my_numbers.end(), [](int a, int b) {
return a < b;
});
for (int i = 0; i < my_numbers.size(); i++)
{
std::cout << "value is " << my_numbers[i] << std::endl;
}
///使用=来捕获外部的所有变量,会把外部的所有变量拷贝一份到 lambda内部
///格式大概像这样
int my_i = 100;
auto fun_my_i = [=] {
std::cout << "fun_my_i i is " << my_i << std::endl;
};
///引用的用[&],所有外部变量皆可引用
int my_i_2 = 100;
auto fun_my_i_2 = [&] {
std::cout << "my_i_2 is " << &my_i_2 << std::endl;
};
///复制并引用捕获
int a1 = 100, a2 = 200;
std::cout << "a1=" << a1 << std::endl;
cout << "a2=" << a1 << endl;
//这里是所有变量拷贝一份,a2则使用引用
auto fun_a = [=, &a2] {
std::cout << "a1=" << &a1 << std::endl;
cout << "a2=" << &a1 << endl;
};
fun_a();
//引用或者复制
int b1 = 100, b2 = 200;
cout << "b1 =" << b1 << endl;
cout << "b2 = " << b2 << endl;
auto fun_b = [b1] {
cout << "b1==" << b1 << ",b1=(引用)" << &b1 << endl;
};
fun_b();
/// this类型的捕获
Test test;
test.lambda();
return 0;
}
输出
$ 函数
下标x is 1 ;
下标x is 2 ;
下标x is 3 ;
下标x is 4 ;
下标x is 5 ;
4
x ====10
20
value is 1
value is 1
value is 2
value is 5
value is 43
value is 77
value is 98
value is 400
a1=100
a2=100
a1=0x16bb08de0
a2=0x16bb08de0
b1 =100
b2 = 200
b1==100,b1=(引用)0x16bb08dcc
test hello