时间:2019-05-06 标签:c++find_iflambda

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13394000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:15:23  来源:igfitidea点击:

c++ find_if lambda

c++lambda

提问by Daniel

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.

下面的代码有什么问题?如果结构体的第一个成员等于 0,它应该在结构体列表中找到一个元素。编译器抱怨 lambda 参数不是谓词类型。

#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; } );
}

回答by billz

Code works fine on VS2012, just one recommendation, pass object by reference instead of pass by value:

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

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