C++ 中的 Lambda 函数、参数和逻辑

Lambda function, arguments and logic in c++

我不熟悉在 C++ 中使用 lambda 函数。我一直在研究网络,找到了几篇文章,解释了 lambda 函数的语法和用途,但我还没有找到清楚地解释如何编写 lambda 函数的内部逻辑的文章。

例如

在 c++ 中对向量进行降序排序时:

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

上面的代码是我写的。在这里,我有几个问题:

  1. 为什么我在lambda函数中只提供两个参数?为什么不是三个?或者为什么我不给出所有的 n 参数(n 是向量的大小)并做一个逻辑?我不是想找到两个元素的最大值,我是想对一个向量进行排序,为什么我应该只考虑两个值?

  2. 为什么a > b给出降序?为什么不是 b > a? lambda 函数中有任何排序吗?

  3. 上述lambda函数中的return值是false(0)还是true(1)?为什么我只需要 return false(0) 或 true(1) 来排序?为什么我不能 return 一个字符来排序,比如让我们假设 return 值 'a' 是升序而 return 值 'd' 是降序?

再次

寻找最大偶数元素时

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

我 returning b > a。而不是a大于b。 ???

如有任何建议,我们将不胜感激。

您的问题与 lambda 无关,但与 std::sort 函数有关。

确实,如果您阅读有关第三个参数(比较函数,在您的情况下为 lambda)的文档,它会说:

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);

确实,不需要创建lambda 来将其作为第三个参数传递。您可以传递任何接收两个类型 T 参数(容器元素之一)和 returns bool.

的函数对象

例如,您可以这样做:

#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;

}