Hello ,
I have discovered lambda function in c++. So this blog is going to be about how to use lambda functions a.k.a anonymous function in writing code involving STL algorithms.
I wanted to write about the lambda long ago but got busy on other stuffs.
[capture_list] (parameters) -> return_type
{
...
...body goes here
...
};
Now let go through the syntax and parts of the lambda functions:
[capture lists] => capture list are the variable name from the outer scope which you want to bring to scope of the lambda definition; lamda function has there local scope and variable defined in the caller scope is not available.
e.g void func_foo(string useme) { usme += "["; auto makeJson = [&useme] () -> std::string { // Bring useme variable in lambda scope useme += "\"object\":null"; }; /// I have used auto keyword to hold the lambda definition /// lambda can be pretty much defined everywhere makeJson() ; // calling syntax is same as general function }
parameters => parameters are the usual parameters in the function definition
void func_foo(string useme) { usme += "["; auto makeJson = [&useme] (std::string value) -> std::string { // Bring useme variable in lambda scope useme += "\"object\":\"" + value +"\""; }; /// I have used auto keyword to hold the lambda definition /// lambda can be pretty much defined everywhere makeJson("isnotnull"); }
return_type => return type can be any object or data type defined before As in the above examples "std::string" is the return type
[body_definition] => body definition can be any c++ statement or expression
Well, that was lambda introduced in c++11 and few more features has been added after that.
Feel free to contact and Let me know if there is any error or further edits required.