1

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?

Vadim Kotov
  • 7,103
  • 8
  • 44
  • 57
  • 1
    Does this answer your question? [What is a lambda expression in C++11?](https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11) – bereal May 14 '21 at 10:37
  • If the dupe suggestions doesn't answer your question, maybe you can elaborate on what you mean by "how is it evaluated"? – Sebastian Redl May 14 '21 at 10:40
  • I recommend two books - "Functional Programming in C++" by Cukic, and "C++ Lambda Story" by Filipek - links - https://www.amazon.co.uk/Functional-Programming-C-Ivan-Cukic/dp/1617293814 and https://www.amazon.co.uk/Lambda-Story-Everything-Expressions-Modern/dp/B08VLM1R76 – Den-Jason May 14 '21 at 10:44
  • Check https://en.cppreference.com/w/cpp/language/lambda and https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11 – Abanoub Asaad May 14 '21 at 10:47
  • 1
    "Here- for each element from begin to end; myfunction is called." with the lambda its the same. What exactly do you not understand? – 463035818_is_not_a_number May 14 '21 at 10:51
  • note that you can still edit your question to clarify. Issue is that if you understand what happens when passing `myfunction`, its not obvious what you don't understand with the lambda. Its not really a "But..", rather "And similar happens when we replace it with a lambda..." – 463035818_is_not_a_number May 14 '21 at 11:31

0 Answers0