jeudi 23 septembre 2021

Lambda function, arguments and logic in c++ [duplicate]

I am new to using lambda functions in C++. I have been researching the web, and found several articles, explaining the syntax and purpose of lambda function, but I have not come found articles which are clearly giving an explaining how to write the inner logic of a lambda function.

For example

During sorting a vector in c++ in decreasing order:

sort(v1.begin(), v1.end(), [](const int &a, const int &b){return b < a;});

I write the above code. Here, I have a few questions:

  1. Why do I only provide two parameters in the lambda function? Why not three? or why not I give all the n parameter(n is size of vector) and do a logic? I am not trying to find maximum of two elements, I am trying to sort a vector, why should I only consider two values?

  2. Why does a > b gives descending order? Why not b > a? Are there any kind of ordering inside the lambda function?

  3. The return value in the above lambda function is either false(0) or true(1)? Why do I only have to return false(0) or true(1) to sort? Why can't I return a character to sort, like let's suppose for return value 'a' it is ascending and return value 'd' it is descending?

Again

During finding the max even element

itr = max_element(v1.begin(), v1.end(), [](const int &a, const int &b){
            if (isEven(a) && isEven(b)) {
                return (a < b);
            } else
                return false;
        }
        );

I am returning b > a. Rather than a greater than b. ???

Any suggestion would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire