当前位置:网站首页>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 !
边栏推荐
- How to do the project of computer remote company in foreign Internet?
- Paddleocr tutorial
- 【雅思阅读】王希伟阅读P3(Heading)
- Is it safe to open an account in the College of Finance and economics? How to open an account?
- [论文阅读] TUN-Det: A Novel Network for Thyroid Ultrasound Nodule Detection
- P3304 [sdoi2013] diameter (diameter of tree)
- 跨域请求
- P4408 [NOI2003] 逃学的小孩(树的直径)
- 雅思考试流程、需要具体注意些什么、怎么复习?
- 巩固表达式C# 案例简单变量运算
猜你喜欢
Hong Kong Jewelry tycoon, 2.2 billion "bargain hunting" Giordano
海思3559万能平台搭建:YUV422的踩坑记录
[path planning] RRT adds dynamic model for trajectory planning
Parsing of XML
Using the uniapp rich text editor
Tester's algorithm interview question - find mode
如何用快解析自制IoT云平台
[IELTS reading] Wang Xiwei reads P4 (matching2 paragraph information matching question [difficult])
[kotlin] the third day
如何有效对直流列头柜进行监测
随机推荐
Fs8b711s14 electric wine bottle opener MCU IC scheme development special integrated IC
如果炒股开华泰证券的户,在网上开户安全吗?
JS how to realize array to tree
如何在外地外网电脑远程公司项目?
Meet ThreadPoolExecutor
Remember to build wheels repeatedly at one time (the setting instructions of obsidian plug-in are translated into Chinese)
French scholars: the explicability of counter attack under optimal transmission theory
How to save your code works quickly to better protect your labor achievements
Réseau graphique: Qu'est - ce que le Protocole d'équilibrage de charge de passerelle glbp?
跨域请求
【路径规划】RRT增加动力模型进行轨迹规划
股票账户佣金怎么调低,炒股佣金怎么调低网上开户安全吗
In June, the list of winners of "Moli original author program" was announced! Invite you to talk about the domestic database
如何避免电弧产生?—— AAFD故障电弧探测器为您解决
Microservice
用快解析内网穿透实现零成本自建网站
Application of fire fighting system based on 3D GIS platform
What is the difference between port mapping and port forwarding
[Peking University] tensorflow2.0-1-opening
Acwing164. Accessibility Statistics (topological sorting +bitset)