0
Lambda expression in c++.
I recently came across lambda in c++. I'm having hard time to understand how it works. For example: sort(v.begin(),v.end(),[ ](cont int& a,cont int& b) -> bool{ return a>b; }); Here, v is a vector of elements. Lambda allows us to write inline functions. But how is this function works sort() stl itself sorts the data then what does this lambda function does? It will be really helpful if someone explains with simple to complex examples.
5 Answers
+ 1
The lambda defines the criteria to sort by. You could e.g. use it to have all 42s first and then the rest descending.
DoMan See example code
https://code.sololearn.com/cDTAPt8QZGC3/?ref=app
0
Manu_1-9-8-5
auto rule = [] (int a, int b) -> bool
{
return a == 42 || (b != 42 && a <b);
}
Here, I changed a>b to a<b and getting output as 42 42 1 2 3.
so, there is a vector when this function is called in sort(). what will be a and b?
I'm unable to understand the return statement.
0
The sort algorithm compares two elements to see which one has to come first. With the lambda you define if a should be before b, by return true else you return false.
Side Note: For elements which have an equal score you would typically return true, so that their positons do not have to be swapped.
0
Ok Manu_1-9-8-5 So, the lamda is like a custom thing which will implement the functionality but provide custom changes.
0
Exactly. You do that to implement general stuff without having to know every detail. Very effective also to separate concerns.