example-
1.for_each(myvector.begin(), myvector.end(), myfunction)
Here- for each element from begin to end; myfunction is called.
But we can replace with lambda function like this-
void printVector(vector<int> v)
{
// lambda expression to print vector
for_each(v.begin(), v.end(), [](int i)
{
std::cout << i << " ";
});
cout << endl;
}
main()
{
vector<int> v {4, 1, 3, 5, 2, 3, 1, 7};
printVector(v);
}
How is this lambda evaluated?
2.Another example-
vector<int>:: iterator p = find_if(v.begin(), v.end(), [](int i)
{
return i > 4;
});
cout << "First number greater than 4 is : " << *p << endl;
How is this lambda evaluated?
3.Another example-
sort(v.begin(), v.end(), [](const int& a, const int& b) -> bool
{
return a > b;
});
printVector(v);
How is this lambda evaluated?
4.Another example-
int count_5 = count_if(v.begin(), v.end(), [](int a)
{
return (a >= 5);
});
cout << "The number of elements greater than or equal to 5 is : "
<< count_5 << endl;
How is this lambda evaluated?