Lambda

时间:2018-01-05 20:24:46

标签: c++

我有问题。首先,考虑这个被称为探索的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个整数值)等于行和col:

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

1 个答案:

答案 0 :(得分:1)

如果要将谓词传递给查找实用程序,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的参数,以避免在每次调用函数时来回复制向量。