c ++ find_if lambda

时间:2012-11-15 08:45:27

标签: c++ lambda

以下代码有什么问题?如果第一个结构的成员== 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; } );
}

1 个答案:

答案 0 :(得分:34)

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

list<S>::iterator it = find_if(l.begin(), l.end(), [] (const S& s) { return s.S1 == 0; } );
相关问题