c ++ find_if lambda

Dan*_*iel 35 c++ lambda

下面的代码有什么问题?如果struct的第一个memebers == 0,它应该在结构列表中找到一个元素.编译器抱怨lambda参数不是Predicate类型.

#include <iostream>
#include <stdint.h>
#include <fstream>
#include <list>
#include <algorithm>

struct S
{
    int S1;
    int S2;
};

using namespace std;

int main()
{
    list<S> l;
    S s1;
    s1.S1 = 0;
    s1.S2 = 0;
    S s2;
    s2.S1 = 1;
    s2.S2 = 1;
    l.push_back(s2);
    l.push_back(s1);

    list<S>::iterator it = find_if(l.begin(), l.end(), [] (S s) { return s.S1 == 0; } );
}
Run Code Online (Sandbox Code Playgroud)

bil*_*llz 37

代码在VS2012上工作正常,只有一个建议,通过引用传递对象而不是传递值:

list<S>::iterator it = find_if(l.begin(), l.end(), [] (const S& s) { return s.S1 == 0; } );
Run Code Online (Sandbox Code Playgroud)

  • [&] <---将通过引用捕获外部变量,也可以通过引用传递对象(S&s) (8认同)