In this blog we will discuss, What is a Lambdas in C++ ? and How to use Lambda function as callbacks ?
1) Using [=] : Outer scope elements has been passed by value
Example:
2) Using [&] : Outer scope elements has been passed by reference
Example:
Lets see example to pass outer scope elements:
Exmaple 1 :
Example 2: ( Mixing capturing by value and Reference )
What is a Lambda Function?
Lambda functions are a kind of anonymous functions in C++. Lambda function is work like a normal function .
- Input - pass arguments
- Output - returns result
Lambda function doesn’t have any name. Its mainly used to create very small functions to pass as a callback to an another API.
Lets start with what was the need of lambda functions ?
Suppose I have an array of int and I want to transverse array using STL algorithm std::for_each.
#include <iostream> #include <algorithm> void display(int a) { std::cout<<a<<" "; } int main() { int arr[] = { 1, 2, 3, 4, 5 }; std::for_each(arr, arr + sizeof(arr) / sizeof(int), &display); std::cout << std::endl; }Now with Lambdas :
#include <iostream> #include <algorithm> int main() { int arr[] = { 1, 2, 3, 4, 5 }; std::for_each(arr, arr + sizeof(arr) / sizeof(int), [](int x) { std::cout <<x <<" "; }); std::cout << std::endl; }Here, without creating extract function we can display array elements, It is more readable than first example.
- [] is used to pass the outer scope elements (passed by value or passed by reference)
- (int x) is showing argument x is passed
Basic Syntax for Lambda Expressions
The following line shows the basic syntax for C++11 lambda expressions:
[ captures ] (parameters) -> returnTypes { lambda Statements; }
- [ captures ]: The capture clause, specifies which outside variables are available for the lambda function and whether they should be captured by value or by reference. An empty capture clause [] means nothing captured, in this case lambda expression body doesn't access variables in the enclosing scope.
- ( parameters ): This is the optional parameters list, you can omit the parameters list if you want a function that takes zero arguments.
- -> returnType: This is the optional return type. Most of the time, compilers can find the return type of the lambda expression when you have zero or one return statement. However, it is good to write return type to understand the code.
- { lambda Statements; }: This is the lambda body. The statements within the lambda body can the captured variables and the parameters.
Pass Outer scope elements inside lambda functions:
Example:
[=](int &x) {}
2) Using [&] : Outer scope elements has been passed by reference
Example:
[&](int &x) {}
Lets see example to pass outer scope elements:
Exmaple 1 :
#include <iostream> #include <algorithm> int main() { int arr[] = { 1, 2, 3, 4, 5 }; int add = 5; std::for_each(arr, arr + sizeof(arr) / sizeof(int), [&](int x) { std::cout << x << " "; // Can modify the add inside this lambda function because // Can modify the add inside this lambda function because // all outer scope elements has write access here. add = 3; }); std::cout << std::endl; std::for_each(arr, arr + sizeof(arr) / sizeof(int), [=](int &x) { x= x+add; // Can not modify the add inside this lambda function because // all outer scope elements has read only access here. // add = 9; }); std::cout << std::endl; std::for_each(arr, arr + sizeof(arr) / sizeof(int), [](int x) { // No access to add inside this lambda function because // all outer scope elements are not visible here. //std::cout << add << " "; }); std::cout << std::endl; }
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int sum = 0; int divisor = 3; vector<int> numbers { 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 }; for_each(numbers.begin(), numbers.end(), [divisor, &sum] (int y) { if (y % divisor == 0) { cout << y << endl; sum += y; } }); cout << sum << endl; }
Here :
- [=, &sum]: Captures any referenced variable within the lambda by value, except sum that has to be captured by reference.
- [&, divisor]: Captures any referenced variable within the lambda by reference, except divisor that has to be captured by value..
Passing Lambda Expressions with std::function:
Example:
Here I provided some example for Lambdas in C++. There are many more things about Lambda Function, I will provide more details about Lambda in my next blogs.
#include <iostream> #include <algorithm> #include <vector> #include <functional> using namespace std; void for_each(std::function<void (int)> func) { vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 }; for_each(numbers.begin(), numbers.end(), func); } int main() { auto func1 = [](int y) { cout << y << endl; }; auto func2 = [](int z) { cout << z * 2 << endl; }; for_each(func1); for_each(func2); }The for_each function receives a std::function<void (int)>, so it is possible to call this function with a lambda expression that returns void and receives an int as an argument.
Here I provided some example for Lambdas in C++. There are many more things about Lambda Function, I will provide more details about Lambda in my next blogs.
1xbet | 1xbet | Bet with a Bonus - RMC | Riders Casino
ReplyDelete1XBet https://septcasino.com/review/merit-casino/ allows you to bet on any favourite horse races or 1xbet korean any other bsjeon.net sporting event. ✓ Get up to £300 토토 + 200 Free Spins casinosites.one No Deposit