【问题标题】:Fails to capture in a lambda无法在 lambda 中捕获
【发布时间】:2017-03-05 00:03:27
【问题描述】:

这是一个可重现的代码

#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 和包括Error: variable “cannot be implicitly captured because no default capture mode has been specified” 在内的一些 SE 帖子,但我没有看到我的错误。

【问题讨论】:

    标签: c++ lambda compiler-errors compilation c++14


    【解决方案1】:

    您将 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()
    

    【讨论】:

    • 谢谢+1!如果我可以问一个后续问题,对于诸如 binary_search_if 之类的二分搜索,是否有与 find_if 等效的方法?
    • @Remi.b - 据我所知...不:没有。
    【解决方案2】:

    如果您想坚持使用std::find,它在第三个参数处希望比较的值,您需要提供一个operator== 来执行比较。

    你可以试试这样的:

    (...)
    bool operator==(const X& x, int b)
    {
        return x.a == b;
    }
    

    并将std::find 更改为:

    std::find(
        v.begin(),
        v.end(),
        y
    ) == v.end()
    

    但我更喜欢将std::find 更改为std::find_if

    【讨论】:

      猜你喜欢
      • 2020-08-23
      • 2018-02-06
      • 2015-10-28
      • 1970-01-01
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多