in c++ lambda function is quite popular. And it makes code more readable with tons of functionality. So let's start learning about it π.
When we talking about the syntax of lambda function in c++ it quite different.
We don't follow complex code on the learning path, we always try to make things simpler.
[ captures ] ( params ) -> return_type { body_statements }
First, we try to understand about captures. When we need variables that defined in outside of function then we use captures to making a clone of a variable.
[ ] { } // no captures
[=] { } // everything by copy(not recommended)
[&] { } // everything by reference(not recommended)
[x] { } // x by copy
[&x] { } // x by reference
[&, x] { } // x by copy, everything else by reference
[=, &x] { } // x by reference, everything else by copy
If we capture by copy that's make the clone of the variable only, they don't affect actual variables. But when we capture by reference we able to change the value of the variable inside that function.
- Try to understand lambda function with Hello World program.
auto say_hello = [] {
cout << "Hello World!";
};
- use a variable that defines outside the function.
// init varible with value
int a = 10;
// lambda function
auto print_a = [a] ( ) {
cout << a;
};
print_a(); \\ output is 10
- change the value of a variable that defines outside the function.
// init varible with value
int a = 10;
// lambda function
auto print_a = [a] ( ) {
a = 12;
cout << a;
};
print_a(); \\ output is 12
Now I think the concept of captures is pretty clear.
Now we move forward to params, params are nothing but the only short name of parameters. I think you all familiar with this concept π₯±. but still, I want to give a short example of parameters in lambda function.
auto sum = [](int a, int b) {
return a + b;
}
cout << sum(10,4); // Output is 14
Now last is return_type, After c++ 20 return type is optional. We don't need to specify the return type of lambda function.
But still we may specify return type with using -> sign.
auto sum = [](int a, int b) -> int {
return a + b;
};
πβ¨β¨πππππβ¨β¨ππππ
Congratulation you learn c++ lambda function in few minutes with dvlpr_roshan ( Roshan Kumar ).
Still, who wants to learn lambda function a little bit more with advance features.
- actually real syntax of the lambda function in c++ is:
[ captures ] <tparams> ( params ) specifiers exception attr -> return_type {body_statements}
Following links can helpful for learning more about the concept of the lambda function in c++.
Top comments (0)