当前位置:网站首页>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 !
边栏推荐
- 取得PMP證書需要多長時間?
- 如果炒股开华泰证券的户,在网上开户安全吗?
- Specification for fs4061a boost 8.4v charging IC chip and fs4061b boost 12.6V charging IC chip datasheet
- URL和URI
- Enterprise application business scenarios, function addition and modification of C source code
- Tester's algorithm interview question - find mode
- C语言中sizeof操作符的坑
- 使用快解析搭建自己的minecraft服务器
- Remember to build wheels repeatedly at one time (the setting instructions of obsidian plug-in are translated into Chinese)
- Build your own minecraft server with fast parsing
猜你喜欢
Illustrated network: what is gateway load balancing protocol GLBP?
如何避免电弧产生?—— AAFD故障电弧探测器为您解决
Detailed explanation of openharmony resource management
香港珠宝大亨,22亿“抄底”佐丹奴
人脸识别5- insight-face-paddle-代码实战笔记
Parsing of XML
The company needs to be monitored. How do ZABBIX and Prometheus choose? That's the right choice!
[JS] - [sort related] - Notes
In the enterprise, win10 turns on BitLocker to lock the disk, how to back up the system, how to recover when the system has problems, and how to recover quickly while taking into account system securi
雅思考试流程、需要具体注意些什么、怎么复习?
随机推荐
企业应用业务场景,功能添加和修改C#源码
Hong Kong Jewelry tycoon, 2.2 billion "bargain hunting" Giordano
快解析——好用的内网安全软件
如何在外地外网电脑远程公司项目?
Go pit - no required module provides Package: go. Mod file not found in current directory or any parent
Skills in analyzing the trend chart of London Silver
模板的进阶
French scholars: the explicability of counter attack under optimal transmission theory
The company needs to be monitored. How do ZABBIX and Prometheus choose? That's the right choice!
Date time type and format in MySQL
如何报考PMP项目管理认证考试?
公司要上监控,Zabbix 和 Prometheus 怎么选?这么选准没错!
【监控】zabbix
同事的接口文档我每次看着就头大,毛病多多。。。
P4408 [noi2003] truant children (tree diameter)
PermissionError: [Errno 13] Permission denied: ‘data. csv‘
挖财学院开户安全的吗?开户怎么开?
AcWing164. 可达性统计(拓扑排序+bitset)
The pit of sizeof operator in C language
Instructions for go defer