c++ - lambda : the function is not captured 的 Lambda

标签 c++ c++11 lambda std-function

以下程序无法编译:

#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

这是什么意思以及如何解决问题?

最佳答案

您在 asort() 内的 lambda 中使用了 f 参数,但没有捕获它。尝试将 f 添加到捕获列表(将 [] 更改为读取 [&f])。

关于c++ - lambda : the function is not captured 的 Lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13461538/

相关文章:

c++ - 从成员初始化列表中调用普通的 void 函数?

c++ - 返回对内部对象的引用时的常量性

c++ - std::launch::async 像同步进程一样阻塞

c++ - 将函数传递给模板

c++ - 使一个类或结构成为所有模板实例化类的 friend ?

python - 是否可以使用pandas中的groupby来执行applymap?

c++ - C++的一些设计问题

c++ - opencv::Mat 是什么类型的对象?它是 shared_ptr 还是 auto_ptr ?它是一个指针吗?

java - 使用 Java 8 流生成整数对

python - python中的lambda可以迭代dict吗?