C++Lambda匿名函数(详解)
2020-04-07 12:14
2336 查看
C++Lambda匿名函数(详解)
一、介绍
使用场景:对于一些简单的函数程序只需要简单的使用一下,但是一般情况下是需要声明定义再使用这个函数。为了解决这个问题,C++11提出了匿名函数机制,可以不取函数名,当场定义当场使用,方便程序员编写程序。典型的匿名函数使用场景是在return语句中写出测试表达式和比较表达式。
二、使用
使用格式如下:
int n = [](int x,int y)->int{return x*y;}(3,4);
(a)(a)(a)其中[]是环境变量声明,指出函数体中对外层作用域中的自动变量的使用限制,也就是匿名函数以什么形式访问函数外部定义的变量。几种格式如下所示:
1、空:不能使用匿名函数外部的变量,只能使用输入的变量如上的(3,4);
2、&:按照引用的方式使用外层作用域中的自动变量,可以改变变量的值。如下所示:
{ int m,n,k; ... [&](int x)->int{k++;m++;n++;return x+k+m+n;} }
3、=:按值的方式使用外层作用域中的自动变量,不能改变变量的值。如下所示:
{ int m,n,k; ... [=](int x)->int{return x+k+n;} }
4、混合使用=,&:可用=、&加外部变量名来混合使用,中间用逗号隔开。如下所示
{ int m,n,k; ... [&k,=](int x)->int{k++;return k+m+n+x;} }
(b)(b)(b)(<形式参数表>):如果函数没有参数,则此项可省略。
(c)(c)(c) -><返回值类型指定>:指定返回值类型。
(d)(d)(d)如果函数多次使用一个匿名函数,则可以给匿名函数取个名。
auto mod3=[](int x){return x%3==0;}
三、实例代码
//lambda.cpp -- lambda expressions //功能:随机生成一个随机整数列表,并判断其中多少个整数可以被3整除,多少个整数可被13整除。 #include <iostream> #include <vector> #include <algorithm>//使用count_if #include <cmath> #include <ctime> const long Size1 = 39L;//加L是进行预处理,告诉编译器这个数是long型的。 const long Size2 = 100 * Size1; const long Size3 = 100 * Size2; bool f3(int x) { return x % 3 == 0; } bool f13(int x) { return x % 13 == 0; } int main() { using std::cout; std::vector<int> numbers(Size1); std::srand(std::time(0)); std::generate(numbers.begin(), numbers.end(), std::rand); //using function pointers cout << "Sample size" << Size1 << "\n"; int count3 = std::count_if(numbers.begin(),numbers.end(),f3); cout << "Count of numbers divisible by 3:" << count3 << '\n'; int count13 = std::count_if(numbers.begin(),numbers.end(),f13); cout << "Count of numbers divisible by 13:" << count13 << "\n\n"; //increase number of numbers numbers.resize(Size2); std::generate(numbers.begin(), numbers.end(), std::rand); cout << "Sample size = " << Size2 << "\n"; //using a functor class f_mod { private: int dv; public: f_mod(int d=1):dv(d){} bool operator()(int x) { return x % dv == 0; } }; count3 = std::count_if(numbers.begin(),numbers.end(),f_mod(3)); cout << "Cout of numbers divisible by 3:" << count3 << "\n"; count13 = std::count_if(numbers.begin(),numbers.end(),f_mod(13)); cout << "Count of numbers divisible by 13:" << count13 << "\n\n"; //increase number of numbers again numbers.resize(Size3); std::generate(numbers.begin(),numbers.end(),std::rand); cout << "Sample size=" << Size3 << '\n'; //using lambds count3 = std::count_if(numbers.begin(), numbers.end(), [](int x) {return x % 3 == 0; }); cout << "Count of numbers divisible by 3:" << count3 << "\n"; count13 = std::count_if(numbers.begin(), numbers.end(), [](int x) {return x % 13 == 0; }); cout << "Count of numbers divisible by 13:" << count13 << "\n"; return 0; }
运行结果:
- 点赞
- 收藏
- 分享
- 文章举报