Lambda表达式

来源:互联网 发布:简述数据库系统的特点 编辑:程序博客网 时间:2024/06/05 02:48
Lambda 表达式

flyfish 2014-10-10

Lambda 表达式也又称为 lambda,就像匿名函数,一个没有函数名字,只有函数体

一 匿名函数到lambda表达式的转变
1  函数
int fun(int x, int y)
{
return x + y;
}  

2  将函数写成一行是:
int fun(int x, int y){ return x + y; }  

3  去掉函数名字之后是:
int (int x, int y) { return x + y; }

4  lambda表达式是:

auto n= [](int x, int y) { return x + y; };

lambda与普通函数的区别是没有函数名字了,多了一对方括号[]

建立windows控制台应用程序

函数式写法

#include "stdafx.h"#include <iostream>int fun(int x, int y){  return x + y;}  int _tmain(int argc, _TCHAR* argv[]){std::wcout<<fun(1,2)<<std::endl;return 0;}

lambda表达式写法
#include "stdafx.h"#include <iostream>  int _tmain(int argc, _TCHAR* argv[]){auto var= [](int x, int y) { return x + y; };std::wcout<<var(1,2)<<std::endl;return 0;}


通过对比,lambda可以实现函数的现写现用,是个语法糖。糖法糖(Syntactic sugar),是由英国计算机科学家Peter J. Landin发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。

二 [ ] 捕获(capture)

1 通过值捕获局部变量a (capture a by value)

#include <iostream>#include "stdafx.h"int _tmain(int argc, _TCHAR* argv[]){int a = 3;auto var = [a] (int x, int y){ return a + x + y; };std::wcout <<var(10,20) << std::endl;}
输出33

2 通过引用捕获局部变量a (capture a by reference)
#include <iostream>#include "stdafx.h"int _tmain(int argc, _TCHAR* argv[]){int a = 3;auto var = [&a] (int x, int y){ return a + x + y; };a = 4;std::wcout <<var(10,20) << std::endl;}

输出34, 通过引用捕获 a,当a被重新赋值时就会影响该表达式的结果


捕获规则
只有 在lambda 中使用的那些变量会被捕获

[]  不捕获任何变量
[&] 引用方式捕获所有在lambda 中使用的变量 
[=]  值方式捕获所有在lambda 中使用的变量
[=, &factor] 以引用捕获factor, 其余变量都是值捕获
[factor] 以值方式捕获factor; 不捕获其它变量
[factor1,&factor2] 以值方式捕获factor1; 以引用方式捕获factor2
[this] 捕获所在类的this指针


例如
auto var = [a] (int x, int y){ return a + x + y; };
可变为 
auto var = [=] (int x, int y){ return a + x + y; };

auto var = [&a] (int x, int y){ return a + x + y; };
可变为
auto var = [&] (int x, int y){ return a + x + y; };


3 捕获this指针,访问类的成员变量

#include "stdafx.h"#include <algorithm>#include <iostream>#include <vector>class CCalc {public:explicit CCalc(int nFactor): m_nFactor(nFactor){}void fun(const std::vector<int>& v) const{std::for_each(v.begin(), v.end(),[this](int n) { std::wcout << n * m_nFactor << std::endl; });}private:int m_nFactor;};int _tmain(int argc, _TCHAR* argv[]){std::vector<int> v;v.push_back(1);v.push_back(2);CCalc o(10);o.fun(v);}
输出10,20


以上程序在Visual C++2010下编译通过
0 0
原创粉丝点击