我在 Lambda 上做错了什么

What am I doing wrong with Lambda

本文关键字:错了 什么 Lambda 我在      更新时间:2023-10-16

>我有一个问题。首先,考虑这个名为"探索"的 2D 矢量:

std::vector<std::vector<int>>explored;

现在,考虑一下,我有一个函数,我将这个向量和两个整数传递给它,称为 row 和 col:

bool check(std::vector<std::vector<int>> const explored, int row, int col);

现在,我想为这个 2D 向量实现 std::find 并检查它的向量(顺便说一下,它们都有 2 个整数值(是否等于行和列:

explored[n][0] == row && explored[n][1] == col;

所以,我写了这个:

if(std::find(explored.begin(), explored.end(), [row,col](vector<int> a, int row, int col){ return a[0] == row && a[1] == col;}) == explored.end()){
    return true;
}

我在这里做错了什么?我的编译器(即Xcode GNU(给出了这个错误:

error: invalid operands to binary expression ('const std::__1::vector<int, std::__1::allocator<int> >' and 'const (lambda at /Users/abylikhsanov/CLionProjects/bfs/main.cpp:8:60)')
        if (*__first == __value_)

如果要将谓词传递给查找实用程序,std::find_if就是您要查找的。
此外,请注意,谓词的签名是:

 bool pred(const Type &a);

因此,它将您的示例转换为如下所示的内容:

if(std::find_if(explored.begin(), explored.end(), [row,col](const vector<int> &a){ return a[0] == row && a[1] == col;}) == explored.end()){
    return true;
}

我还使用了一个 const 引用作为 lambda 的参数,以避免每次调用函数时来回复制向量。