c++ - 无法在 lambda 中捕获

标签 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;
}

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

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

我尝试了多种选择并阅读了 this和一些 SE 帖子,包括 Error: variable “cannot be implicitly captured because no default capture mode has been specified”但我没有看到我的错误。

最佳答案

您使用的 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;}

所以编译错误。

所以试试

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

关于c++ - 无法在 lambda 中捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42602843/

相关文章:

c++ - 更强大的集成器 cpp

javascript - 将具有子数组的对象数组映射并减少到具有父 id 的子数组

java - 如何在 groupingBy 操作中使用自定义收集器

python - 我如何将 .py 编译为 .exe?

java - 比较parseInt(String)与Int输入错误: unexpected type Java

c++ - 如何使用索引访问 C++ 结构属性值?

c++ - 点不会通过 OpenGl 中的键盘输入移动

c++ - C++严格混叠规则使用Qt和QLinkedList编译错误

c++ - 使用 boost::phoenix::val 的动机?

c# - 使用 Actions 时,() 在 lambda 表达式中意味着什么?