2017-03-05 194 views
0

这里拍摄是一个可重复的代码不能以拉姆达

#include <iostream> 
#include <vector> 
#include <algorithm> 

class X 
{ 
public: 
int a; 
    X(int b) 
    : a(b) 
    {} 
}; 

int main() 
{ 
    // Build the vector 'v' 
    std::vector<X> v; 
    X x1(7); 
    v.push_back(x1); 
    X x2(11); 
    v.push_back(x2); 
    X x3(16); 
    v.push_back(x3); 
    X x4(20); 
    v.push_back(x4); 
    X x5(22); 
    v.push_back(x5); 
    X x6(31); 
    v.push_back(x6); 
    X x7(38); 
    v.push_back(x7); 

    // Search if there is an element of 'v' which attribute 'a' equals 18 
    int y(18); 
    if (
    std::find(
     v.begin(), 
     v.end(), 
     [&](const X& o){return o.a == y;} 
    ) == v.end() 
    ) 
    { 
    std::cout << "'y' is not present in 'v'\n"; 
    } else 
    { 
    std::cout << "'y' is present in 'v'\n"; 
    } 

    return 0; 
} 

我尝试编译g++ -std=c++14 a.cpp -o a并获得

error: invalid operands to binary expression 
     ('X' and 'const (lambda at a.cpp:38:5)') 

我已经尝试了许多替代和读取this等一批SE的帖子包括Error: variable “cannot be implicitly captured because no default capture mode has been specified”,但我没有看到我的错误。

回答

5

您使用的参数是std::find(),您应该使用std::find_if()

如果您使用std::find()第三个argumend应该是容器的值;在这种情况下,一个class X实例。

如果您希望第三个参数是一元谓词(即接收容器值并返回bool),则正确的功能是std::find_if()

使用一元谓词作为std::find()的第三个参数,编译器尝试将class X实例等同于lambda函数。

即:编译器尝试编译

*(v.begin()) == [&](const X& o){return o.a == y;} 

所以编译器错误。

因此,与

std::find_if( // <-- std::find_if ! 
    v.begin(), 
    v.end(), 
    [&](const X& o){return o.a == y;} 
) == v.end() 
+0

谢谢+1!如果我可能会问一个后续问题,是否存在与'binary_search_if'等二进制搜索类似的'find_if'? –

+0

@ Remi.b - 据我所知...不:没有。 – max66

1

尝试如果你想与std::find,其中,在第三个参数,预期值要坚持进行比较,您需要提供一个operator==进行比较。

你可以尝试这样的事情:

(...) 
bool operator==(const X& x, int b) 
{ 
    return x.a == b; 
} 

,改变std::find到:

std::find(
    v.begin(), 
    v.end(), 
    y 
) == v.end() 

,但我宁愿只是改变std::findstd::find_if