博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Lambda表达式
阅读量:6942 次
发布时间:2019-06-27

本文共 2346 字,大约阅读时间需要 7 分钟。

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 
int fun(int x, int y){ return x + y;} int _tmain(int argc, _TCHAR* argv[]){ std::wcout<
<
lambda表达式写法
#include "stdafx.h"#include 
int _tmain(int argc, _TCHAR* argv[]){ auto var= [](int x, int y) { return x + y; }; std::wcout<
<
通过对照,lambda能够实现函数的现写现用,是个语法糖。糖法糖(Syntactic sugar),是由英国计算机科学家Peter J. Landin发明的一个术语,指计算机语言中加入的某种语法,这样的语法对语言的功能并没有影响,可是更方便程序猿使用。

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

#include 
#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 <
<< std::endl;}
输出33
2 通过引用捕获局部变量a (capture a by reference)
#include 
#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 <
<< 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 
#include
#include
class CCalc {public: explicit CCalc(int nFactor) : m_nFactor(nFactor) { } void fun(const std::vector
& 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
v; v.push_back(1); v.push_back(2); CCalc o(10); o.fun(v);}
输出10,20
以上程序在Visual C++2010下编译通过

转载地址:http://tcinl.baihongyu.com/

你可能感兴趣的文章
Discuz! X 插件开发手册
查看>>
Spring 注解@Component,@Service,@Controller,@Repository
查看>>
让PHP7达到最高性能的几个Tips(转)
查看>>
朗文在线词典的使用
查看>>
7-9-有向无环图拓扑排序-图-第7章-《数据结构》课本源码-严蔚敏吴伟民版
查看>>
求最短路径的三种算法: Ford, Dijkstra和Floyd
查看>>
(求助大牛)关于vs2010上的AVS代码bug问题~~
查看>>
JQuery上传插件Uploadify使用详解
查看>>
重构第26天 移除双重否定(Remove Double Negative)
查看>>
均值、方差、标准差及协方差、协方差矩阵详解
查看>>
oracle 清除当前用户的回收站
查看>>
有些事必须去做——写在离职之后创业之前
查看>>
转python调用Go代码
查看>>
红黑树(一)之原理和算法的详细分析【转】
查看>>
undefined reference to typeinfo - C++ error message
查看>>
springmvc: 普通list数据输出json
查看>>
8127 timeout!!! 搞死人啊
查看>>
Android开发 设置开机自动启动
查看>>
高德地图iOS SDK限制地图的缩放比例
查看>>
【组件化开发】前端进阶篇之如何编写可维护可升级的代码
查看>>