Lambda的Lambda:未捕获功能 [英] Lambda of a lambda : the function is not captured

查看:93
本文介绍了Lambda的Lambda:未捕获功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序无法编译:

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
#include <cstdlib>
#include <cmath>

void asort(std::vector<double>& v, std::function<bool(double, double)> f)
{
    std::sort(v.begin(), v.end(), [](double a, double b){return f(std::abs(a), std::abs(b));});
}

int main()
{
    std::vector<double> v({1.2, -1.3, 4.5, 2.3, -10.2, -3.4});
    for (unsigned int i = 0; i < v.size(); ++i) {
        std::cout<<v[i]<<" ";
    }
    std::cout<<std::endl;
    asort(v, [](double a, double b){return a < b;});
    for (unsigned int i = 0; i < v.size(); ++i) {
        std::cout<<v[i]<<" ";
    }
    std::cout<<std::endl;
    return 0;
}

因为:

error : 'f' is not captured

它是什么的意思和解决方法?

What does it mean and how to solve the problem ?

推荐答案

您使用 f asort()中的lambda中的参数,但您不会捕获它。尝试将 f 添加到捕获列表(将 [] 更改为 [& f] )。

You use the f parameter in the lambda inside asort(), but you don't capture it. Try adding f to the capture list (change [] to read [&f]).

这篇关于Lambda的Lambda:未捕获功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆