无法在lambda中捕获

Rem*_*i.b 0 c++ lambda compiler-errors compilation c++14

这是一个可重现的代码

#include <iostream>
#include <vector>
#include <algorithm>

class X
{
public:
 int a; 
  X(int b)
  : a(b)
  {}
};

int main()
{
  // Build the vector 'v'
  std::vector<X> v;
  X x1(7);
  v.push_back(x1);
  X x2(11);
  v.push_back(x2);
  X x3(16);
  v.push_back(x3);
  X x4(20);
  v.push_back(x4);
  X x5(22);
  v.push_back(x5);
  X x6(31);
  v.push_back(x6);
  X x7(38);
  v.push_back(x7);

  // Search if there is an element of 'v' which attribute 'a' equals 18
  int y(18); 
  if (
    std::find(
        v.begin(),
        v.end(),
        [&](const X& o){return o.a == y;}
      ) == v.end()
    )
  {
    std::cout << "'y' is not present in 'v'\n";
  } else
  {
    std::cout << "'y' is present in 'v'\n";
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我尝试编译g++ -std=c++14 a.cpp -o a并得到

 error: invalid operands to binary expression
      ('X' and 'const (lambda at a.cpp:38:5)')
Run Code Online (Sandbox Code Playgroud)

我已经尝试了许多替代方案并阅读了这篇文章和一些SE帖子,包括错误:变量"无法隐式捕获,因为没有指定默认捕获模式"但我没有看到我的错误.

max*_*x66 5

您正在使用std::find()您应该使用的参数std::find_if().

如果你使用std::find()第三个参数应该是容器的值; class X在这种情况下,一个实例.

如果你想要第三个参数是一元谓词(接收一个容器值并返回一个bool),那么正确的函数是std::find_if().

使用一元谓词作为第三个参数std::find(),编译器尝试将class X实例与lambda函数等同.

那就是:编译器尝试编译

*(v.begin()) == [&](const X& o){return o.a == y;}
Run Code Online (Sandbox Code Playgroud)

所以编译错误.

所以试试吧

std::find_if(  // <-- std::find_if !
    v.begin(),
    v.end(),
    [&](const X& o){return o.a == y;}
  ) == v.end()
Run Code Online (Sandbox Code Playgroud)