首页 > 解决方案 > 在类中声明一个自动 lambda 函数

问题描述

我正在尝试在类中声明一个 lambda 比较函数,如下所示:

class Solve {
private:
    int n, q, first[N+1], depth[N+1], seg[_log(N)+2][(N<<1)+1];
    vector <int> G[N+1], euler;

    auto cmp = [euler, depth] (const int &a, const int &b) -> bool {
        return depth[euler[a]] < depth[euler[b]];
    };
...

但得到错误:error: non-static data member declared with placeholder 'auto'

将函数声明为静态无济于事:error: capture of non-variable 'Solve::euler'+ 一堆其他错误。明确使用 std::function <> 也没有解决它。

该功能旨在用于min(a, b, cmp);

任何帮助是极大的赞赏!

标签: c++classlambdastl

解决方案


无需将 lambda存储在您的类中。您可以在需要时构建一个。

我会为此创建一个方法:

auto MakeComparator() const
{
    return [this](const int &a, const int &b) -> bool
    {
        return depth[euler[a]] < depth[euler[b]];
    };
};

推荐阅读