std :: find_if和lambda引用结构字段

时间:2016-06-02 07:41:53

标签: c++11 lambda stl

this question我们有:

#include <list>
#include <algorithm>

struct S
{
    int S1;
    int S2;
};

int main()
{
    std::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);

    auto it = std::find_if(l.begin(), l.end(), [] (S s)
        { return s.S1 == 0; } );
}

但是,如果我想找到s1.S1的匹配项,我可能会尝试:

auto it = std::find_if(l.begin(), l.end(), [s1.S1] (S s)
    { return s.S1 == s1.S1; } );

但是我遇到了编译器错误。这有效:

auto foo = s1.S1;
auto it = std::find_if(l.begin(), l.end(), [foo] (S s)
    { return s.S1 == foo; } );

我想我理解为什么我需要引入一个临时的简单类型,因为我们可以将[foo]视为函数参数,但查找结构成员的用例似乎是一个常见的要求那么不支持使用的理由是什么?或者有另一种方法可以避免临时变量吗?

1 个答案:

答案 0 :(得分:1)

在C ++ 11中,我认为您已经加入了中间变量。在C ++ 14中,您可以使用带有初始化程序的捕获:

std::list<S>::iterator it = std::find_if(l.begin(), l.end(), 
    [foo = s1.S1] (S s) { return s.S1 == foo; } );
//  ^^^^^^^^^^^^^
相关问题