Lambda expressions allow you to write unnamed inline function for small tasks. They are often used to pass a functionality to another functions.
Examples show lambda usage in STL:
1. Lambda with for_each()
The for_each() function applies a given function to every element in the given range. Lambda expressions are particularly useful with for_each() as shown in the below program:
#include <vector>
#include<iostream>
#include<algorithm>
using namespace std ;
int main()
{
vector<int> v {10, 20, 30};
for_each (v.begin(), v.end(),
[] ( int &x ) { x *= 2 ; });
for_each (v.begin(), v.end(),
[](int x) {cout << x << " " ;});
return 0 ;
}
Output
20 40 60
Explanation:
- The first for_each() uses a lambda function to double each value in the vector.
- Each element is passed by reference (int &x), so the original values are modified.
- The second for_each() uses another lambda to print each element.
- This shows how lambdas can both update and access container elements.
2. Lambda with count_if()
The count_if() function counts the number of elements in the range that satisfy a given condition.
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std ;
int main()
{
vector<int> v {10, 5, 3, 20, 100};
int res = count_if(v.begin(), v.end(),
[](int x) {return x >= 10; });
cout << res << "\n";
return 0 ;
}
Output
3
Explanation: Here, the lambda expression checks if an element x is greater than or equal to 10. count_if returns the number of elements that satisfy this condition, which here are 3 (10, 20, 100).
3. Lambda with find_if()
The find_if() function returns an iterator to the first element that satisfies a given condition.
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std ;
int main()
{
vector<int> v {100, 20, 4, 200, 1};
auto it = find_if(v.begin(), v.end(),
[](int x) { return x < 10;});
cout << *it;
return 0 ;
}
Output
4
Explanation: The lambda expression is used with find_if() to find the first element in the vector v that is less than 10. The iterator to this element is stored in it, and the value at this iterator is then printed.
4. Lambda with accumulate()
The accumulate() function is used to find the sum (or any other binary operation) of all the values lying in a range.
#include<iostream>
#include<numeric>
#include<vector>
using namespace std ;
int main()
{
vector<int> v {10, 2, 4, 20, 1};
int res = accumulate(v.begin(), v.end(), 0);
cout << res << '\n';
res = accumulate(v.begin(), v.end(), 1,
[](int x, int y){return x*y;});
cout << res;
return 0 ;
}
Output
37 1600
Explanation: The first accumulate() call calculates the sum of the elements in v which is its default behaviour. The second accumulate() call uses a lambda expression to perform multiplication for calculating the product of all elements in v.