c++functionc++11lambdastl-algorithm

Lambda function, arguments and logic in c++


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.


Solution

  • Your question has nothing to do with lambdas, but with the std::sort function.

    Indeed, if you read the documentation about the third parameter (the comparison function, the lambda in your case), it says:

    comparison function object which returns ​true if the first argument is less than (i.e. is ordered before) the second.

    The signature of the comparison function should be equivalent to the following:

    bool cmp(const Type1 &a, const Type2 &b);

    Indeed, there is not need to create a lambda to pass it as the third parameter. You can pass any function object that receives two arguments of type T (the one of your container's elements) and returns bool.

    For example, you can do something like this:

    #include <vector>
    #include <algorithm>
    #include <iostream>
    
    struct  {
        bool operator () (int a, int b){
            return a > b;
        }
    }my_comp;
    
    
    
    int main(){
        std::vector<int> v={1,2,3};
    
        std::sort(v.begin(), v.end(), my_comp);
    
    
        for(auto e:v) std::cout << e << " ";
        std::cout << std::endl;
    
    }