1--Lambda表达式
1-1--基本用法
① [] 用于捕获变量,一般用于使用和修改外部的变量,可以为空;
② (int a, int b) 表示参数列表,可以省略;
③ -> int 定义返回类型,一般可以省略,让编译器自动推断;
④ auto f 表示将定义的 lambda 表达式赋值给对象 f,auto 用于自动推断类型;
基本用法如下:
#include <iostream>int main(int argc, char *argv[]){auto f = [](int a, int b) -> int{return a + b;};std::cout << f(1, 2) << std::endl;return 0;
}
1-2--其余用法
① 使用和修改外部变量
通过捕获变量来修改(引用传递)和使用外部变量:
#include <iostream>int main(int argc, char *argv[]){int M = 10, N = 20;auto f = [&M, N](int a, int b){std::cout << "N:" << N << std::endl; // 使用外部变量M = 30; // 修改外部变量return a + b;};std::cout << f(1, 2) << std::endl;std::cout << "M: " << M << std::endl;return 0;
}
② 自定义变量
通过捕获变量来自定义变量,无需出现在外部;
#include <iostream>int main(int argc, char *argv[]){int M = 10, N = 20;auto f = [&M, N, c=3](int a, int b){std::cout << "N:" << N << std::endl; // 使用外部变量M = 30; // 修改外部变量return (a + b) * c;};std::cout << f(1, 2) << std::endl;std::cout << "M: " << M << std::endl;return 0;
}
2--参考
清晰易懂,现代C++最好用特性之一:Lambda表达式用法详解