Vin*_*ent 29 c++ lambda c++11 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;
}
Run Code Online (Sandbox Code Playgroud)
因为:
error : 'f' is not captured
Run Code Online (Sandbox Code Playgroud)
它是什么意思以及如何解决问题?
小智 8
您实际上是在lambda中引用f,它是外部作用域中的变量.您应该在捕获列表中捕获它(最简单的可能是通过引用[&f],或[&]通过引用捕获所有内容,因为您立即使用它).
另一方面,std :: function在执行类型擦除时有一些开销,在这种情况下,引入模板类型可能更好.