简体   繁体   中英

c++ find_if lambda

What is wrong with the code below? It is supposed to find an element in the list of structs if the first of the struct's members equals to 0. The compiler complains about the lambda argument not being of type 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; } );
}

代码在 VS2012 上运行良好,只有一个建议,按引用传递对象而不是按值传递:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM