Table of contents
the lambda expression was first introduced to the programming world after the function pointer as we discussed previously. the function pointer refers to a pointer that holds the address of the function to be used as an argument to another function, in other words, it could be used to make the callbacks of the function inside another function with the address only. you may have used the standard library "sort"- you can customize the sorting operation based on a pointer to the function. well, as you can figure out there are much of overhead and technical talks even in the depth of the pointer to the address of the function.
can I use delete or free with a function pointer?
A: yes, but hard speaking. as the function pointer when passed to another function is stored in the stack of that function and leaves another space to the calls of the function pointer.
briefly, the function pointer is important in many cases but when it comes to lambda we can call the shortcuts of all of that. the function in general cannot access the mainstream function stack. then to access the stack we have to make a copy via argument or passing using references. what if we have something like this?
std::unorderd_map<std::vector<std::pair<long long,long long>>,std::vector<std::pair<long long,long long>>_varName;
even more what if we have two unordered_maps in our calls then it is really annoying and even if we used the #define or modern one using. still paranoid.
Run to lambda!!
then the lambda has proven both efficiency and the durability needed for a small task like sorting unorder_map with two vectors of long long pairs. mmm, you are now super excited to start using lambda everywhere. but how to write lambda?
A good source for the syntax of a language is its documentation. but since you came here we have had two cases
you don't know how to use the documentation
you are looking for the golden spoon
Syntax.
auto func=[capture](arguments){//function call should return something}
the capture has many types the most dangerous is the default capture mode.
[&](int value){return value%divisor==0;};
the divisor is local vars and when local vars move outside the local scope the reference to the value doesn't exist making a dangling pointer.
[=] (int value){return value%divisor==0;};
now the var will not dangle but the by-value capture is not the anti-dangle method. the capture only catches the elements in the current scope- think and take your time to get your gust about that.
That's it for today