当前位置:网站首页>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 !
边栏推荐
- 圖解網絡:什麼是網關負載均衡協議GLBP?
- Actual combat simulation │ JWT login authentication
- Réseau graphique: Qu'est - ce que le Protocole d'équilibrage de charge de passerelle glbp?
- 45 year old professor, she threw two super unicorns
- PMP certificate renewal process
- 用快解析内网穿透实现零成本自建网站
- 同事的接口文档我每次看着就头大,毛病多多。。。
- 使用快解析搭建自己的minecraft服务器
- A new method for analyzing the trend chart of London Silver
- 「运维有小邓」域密码策略强化器
猜你喜欢
Verilog tutorial (11) initial block in Verilog
S32 design studio for arm 2.2 quick start
Netcore3.1 JSON web token Middleware
[JS] - [sort related] - Notes
华为200万年薪聘请数据治理专家!背后的千亿市场值得关注
PMP证书续证流程
快解析内网穿透帮助企业快速实现协同办公
Illustrated network: what is gateway load balancing protocol GLBP?
业务场景功能的继续修改
[kotlin] the third day
随机推荐
Life is changeable, and the large intestine covers the small intestine. This time, I can really go home to see my daughter-in-law...
Data on the number of functional divisions of national wetland parks in Qinghai Province, data on the distribution of wetlands and marshes across the country, and natural reserves in provinces, cities
Go step on the pit - no required module provides package: go mod file not found in current directory or any parent
Face recognition 5- insight face padding code practice notes
"Xiaodeng" domain password policy enhancer in operation and maintenance
22-07-02周总结
股票账户佣金怎么调低,炒股佣金怎么调低网上开户安全吗
如何有效对直流列头柜进行监测
【监控】zabbix
Expand your kubecl function
Hologres Query管理及超时处理
P3304 [SDOI2013]直径(树的直径)
Mit-6.824-lab4b-2022 (10000 word idea explanation - code construction)
P4281 [AHOI2008]紧急集合 / 聚会(LCA)
Fast parsing intranet penetration helps enterprises quickly achieve collaborative office
巩固表达式C# 案例简单变量运算
【报错】 “TypeError: Cannot read properties of undefined (reading ‘split‘)“
The waterfall flow layout demo2 (method 2) used by the uniapp wechat applet (copy and paste can be used without other processing)
使用快解析搭建自己的minecraft服务器
Some basic functions of enterprise projects are developed, and important things are saved to online first a