当前位置:网站首页>lambda expressions
lambda expressions
2022-07-05 00:09:00 【DWQY】
Preface
First contact lambda The expression is still doing leetcode When , There is a scenario using lambda The expression is very convenient , The code is as follows :
static bool cmp() {
...
}
void function() {
...
sort(A.begin(),A.end(),cmp);
...
}
Use STL Of sort() when , To customize the sorting method . At this time, if you want to use function() Local variables in functions are particularly troublesome . While using lambda The expression can pass parameters directly . Of course, it's just lambda The tip of the iceberg of expression , This article will introduce in more detail , I hope this article can clarify several issues :
1.lambda What is an expression and how to use it ?
2.lambda Some principles when using expressions .
Because I often C++, So use C++ As an example language ~
1. What is? lambda expression ?
lambda Expressions can be understood as anonymous inline functions , Inline functions are defined directly at the time of declaration , Generally, there are restrictions , The function body is required to be relatively short . The meaning of anonymity is that there is no need to be specifically for lambda The expression is specially written with a function name .
lambda Function has three main advantages :
1) convenient , You can easily define short and concise functions . Define proximity
2) Don't think about the function name
3) Define immediate execution , Fast calling speed , There is no middle cost
2. How to use lambda expression ?
First look at it. lambda The syntax of the expression :[capture list](parameter list)->return type{function body}
There are four main parts , Each part is defined in detail as follows :
capture list: Capture list ,lambda List of local variables defined in the function
parameter list: parameter list
return type: Function return type
function body: The body of the function
Compared with conventional functions , parameter list , Return type , Function bodies are familiar . So what is a capture list ? This will be mentioned later . Note the location of the return type , Not at the beginning , This comes from lambda Expressions use trailing return types .
Another example ( This is all ):[](ListNode *x, ListNode *y)->bool {return x->val > y->val;}
Although there are four parts , In fact, the parameter list and return type can be ignored , But the capture list and function body must exist
It's all functions , What is the difference between and ordinary functions ?
1)lambda Expressions cannot have default arguments , The shape parameters of real parameters are consistent
2) All parameters must have parameter names
3) Variable parameters are not supported
The rest is the conclusion , The first one will be explained below .
3.lambda Some principles used in expressions
The concept of capture list is left above , I think the use of this is lambda One of the important parts of expression .
If there is no capture list [],lambda Only variables in the parameter list can be used in the body of an expression function , There is no way to use the local variables of the outer function . But put local variables in the capture list ,lambda Expressions can be used .
lambda There are two ways to capture expressions :
The first angle is : Quote capture 、 Worth catching
The second angle is : Ordinary capture Implicit capture Hybrid capture
First of all, introduce their respective concepts , Reference capture is the reference of variables passed , Value capture passes the copy value of the variable . Analogous to parameter passing , It's easy to understand . Display capture is to pass the specific variable name , Implicit capture is to use a flag to represent all . The specific implementation in use is as follows :
[] empty
[ Variable ] Pass only variables Worth catching
[=] All entities Worth catching
[&] Quote all Quote capture
[&, Variable name ] Variable name value capture Other variable references capture
[=, Variable name ] Variable name reference capture , Other variable values are captured
Ordinary capture :[ Variable name ]
Implicit capture :[=] [&]
Hybrid capture : [=, Variable name ] [&, Variable name ]
There are several key points to emphasize :
1) Value capture , Captured by values in lambda Copy the expression when it is created
2) When using reference capture to capture a variable , You must ensure that the referenced object is in the lambda It exists when it is executed
3) In value capture, if you want to modify the value of a variable in the capture list , Need to add mutable, Grammar becomes :[capture list] (parameter list) mutable -> return type {function body}
4) As mentioned above, the return type can be omitted , But conditional :1) The return value is void 2) There is only... In the function body return A word of , The compiler can infer by itself
Dig deeper into the principle , Explain what's left above :lambda Why must there be an argument in an expression ?
Of course, the premise of requiring arguments is that there is something in the parameter list . The reason lies in lambda The essence of expression is to construct classes , The constructed class has no default constructor , Assignment operators and default destructors . Because there is no default constructor , When a function with parameters , Arguments must be provided to construct properly . And the captured variables will be processed in the construction of the class , Captured by values will take parameters as member variables , And reference capture , Parameters are not used as member variables . Find an example for reference :
Example source :https://blog.csdn.net/sgh666666/article/details/89000215
Due to the limited level of the author , If there are mistakes , Please correct in the comments area below , thank you !
边栏推荐
- 巩固表达式C# 案例简单变量运算
- Best practice case of enterprise digital transformation: introduction and reference of cloud based digital platform system security measures
- 多回路仪表在基站“转改直”方面的应用
- uniapp上传头像
- JS how to realize array to tree
- Build your own minecraft server with fast parsing
- Verilog tutorial (11) initial block in Verilog
- The input of uniapp is invalid except for numbers
- JS 将伪数组转换成数组
- 企业应用业务场景,功能添加和修改C#源码
猜你喜欢

海思3559万能平台搭建:YUV422的踩坑记录

XML的解析

Hisilicon 3559 universal platform construction: YUV422 pit stepping record

城市轨道交通站应急照明疏散指示系统设计

45 year old professor, she threw two super unicorns
![[论文阅读] CarveMix: A Simple Data Augmentation Method for Brain Lesion Segmentation](/img/41/eb790e7419a158e985fa503bd7dc17.png)
[论文阅读] CarveMix: A Simple Data Augmentation Method for Brain Lesion Segmentation

Verilog tutorial (11) initial block in Verilog

Hong Kong Jewelry tycoon, 2.2 billion "bargain hunting" Giordano

华为200万年薪聘请数据治理专家!背后的千亿市场值得关注

快解析——好用的内网安全软件
随机推荐
Is it safe to open and register new bonds? Is there any risk? Is it reliable?
Hisilicon 3559 universal platform construction: YUV422 pit stepping record
He worked as a foreign lead and paid off all the housing loans in a year
他做国外LEAD,用了一年时间,把所有房贷都还清了
Ap8022 switching power supply small household appliances ACDC chip offline switching power supply IC
[kotlin] the third day
S32 design studio for arm 2.2 quick start
Hologres Query管理及超时处理
[ODX studio edit PDX] -0.3- how to delete / modify inherited elements in variant variants
Pytoch --- use pytoch to realize linknet for semantic segmentation
Consolidated expression C case simple variable operation
The company needs to be monitored. How do ZABBIX and Prometheus choose? That's the right choice!
人生无常,大肠包小肠, 这次真的可以回家看媳妇去了。。。
Date time type and format in MySQL
Advanced template
Acwing164. Accessibility Statistics (topological sorting +bitset)
The input of uniapp is invalid except for numbers
How to apply for PMP project management certification examination?
模板的进阶
如何避免电弧产生?—— AAFD故障电弧探测器为您解决