pbi*_*t24 14 c++ lambda functional-programming function visual-studio-2013
我正在尝试添加两个c ++ lambda函数。我的意思是:
假设您有两个函数f,g每个函数都有一个或多个参数,那么说f(x,y)和g(x,y)。我想将它们都添加到新的函数h中,如下所示:
h = f + g
Run Code Online (Sandbox Code Playgroud)
评估应该像这样工作:
h(x,y) = f(x,y) + g(x,y)
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经尝试了以下代码,但是它不起作用。末尾的“ cin”正好可以防止控制台自动关闭。
#include <iostream>
#include <functional>
using namespace std;
function<int (int,int)> add(function<int(int, int)> g, function<int(int, int)> f)
{
return [&](int x, int y)->int{return g(x, y) + f(x, y); };
}
int main()
{
int i = 0;
function<int (int,int)> sum = [](int x, int y)->int { return x + y; };
function<int (int,int)> mul = [](int x, int y)->int { return x * y; };
cout << sum(1, 2) << endl;
cout << mul(3, 4) << endl;
function<int(int, int)> s = add(sum, mul);
cout << s(2, 3) << endl;
cin >> i;
}
Run Code Online (Sandbox Code Playgroud)
代码可以编译,但是当我尝试评估s(2,3)时,它将停止工作。它只是说程序停止了工作,我必须关闭它。我正在使用Visual Studio 2013。
有人知道该怎么做吗?还是您知道开箱即用的任何图书馆?
Sto*_*ica 32
真微妙
function<int (int,int)> add(function<int(int, int)> g, function<int(int, int)> f)
{
return [&](int x, int y)->int{return g(x, y) + f(x, y); };
// ^-- This here
}
Run Code Online (Sandbox Code Playgroud)
您捕获g并按f引用保存,并将这些引用存储在std::function返回中。但是这些是对函数局部变量的引用,因此它们在您返回的第二秒就晃晃了。因此,您的代码只是具有未定义的行为。
一个简单的解决方法是按价值捕获[=]。
| 归档时间: |
|
| 查看次数: |
853 次 |
| 最近记录: |