C ++中的lambda函数

时间:2015-07-31 09:10:04

标签: c++ lambda closures

我对lambda函数和闭包的整个概念有点新, 所以我开始写这个简单的程序, 但我在这些线上得到错误,我不知道如何解决它

,输出应为: 在第31行:1 2 5 3

第32行:2 3 6 4

第45行:5 4 3

第49行:3 0 1

第53行:2 2 2

第57行:3 0 1

function <int(int)> F[n], G[n];

for (i = 1; i < n; i++)
{
    F[i] = [&F, &i](int x){ return (x < i) ? x : F[i](x - i); };
    G[i] = [&G, i](int x){ return (x < i) ? x : G[i](x - i); };
}

并且我得到了这些错误:

错误1错误C2065:'function':未声明的标识符d:\ c ++ projects \ tester \ tester \ source.cpp 36 1 tester

错误2错误C2144:语法错误:'int'前面应加')'d:\ c ++ projects \ tester \ tester \ source.cpp 36 1 tester

错误3错误C2059:语法错误:')'d:\ c ++ projects \ tester \ tester \ source.cpp 36 1 tester

错误4错误C2065:'F':未声明的标识符d:\ c ++ projects \ tester \ tester \ source.cpp 40 1 tester

错误5错误C3481:'F':未找到lambda捕获变量d:\ c ++ projects \ tester \ tester \ source.cpp 40 1 tester

错误6错误C2065:'G':未声明的标识符d:\ c ++ projects \ tester \ tester \ source.cpp 41 1 tester

错误7错误C3481:'G':未找到lambda捕获变量d:\ c ++ projects \ tester \ tester \ source.cpp 41 1 tester

错误8错误C2065:'F':未声明的标识符d:\ c ++ projects \ tester \ tester \ source.cpp 45 1 tester

错误9错误C2065:'G':未声明的标识符d:\ c ++ projects \ tester \ tester \ source.cpp 49 1 tester

错误10错误C2065:'F':未声明的标识符d:\ c ++ projects \ tester \ tester \ source.cpp 53 1 tester

错误11错误C2065:'G':未声明的标识符d:\ c ++ projects \ tester \ tester \ source.cpp 57 1 tester

错误12错误C2109:下标需要数组或指针类型d:\ c ++ projects \ tester \ tester \ source.cpp 40 1 tester

错误13错误C2109:下标需要数组或指针类型d:\ c ++ projects \ tester \ tester \ source.cpp 41 1 tester

这是我的整个计划

#include <iostream>

using namespace std;

class Opp
{
  int n;

public:

Opp() : n(0){}
Opp(int x) : n(x){}
Opp(const Opp& Q) : n(Q.n + 1){};

Opp operator ()(int x){ return Opp(x + 2); }

friend void Print(Opp *A, int n){
    for (int i = 0; i < n; i++)
        cout << A[i].n << "\t";
    cout << endl;
 };
};

  int main(int argc, const char * argv[]) {

Opp A = Opp(1), B(2), C = A(3), D(B), P[4];

P[0] = A; P[1] = B; P[2] = C; P[3] = D;

Opp Q[] = { A, B, C, D };

Print(P, 4);
Print(Q, 4);

const int n = 14;
int i;
function <int(int)> F[n], G[n];

for (i = 1; i < n; i++)
{
    F[i] = [&F, &i](int x){ return (x < i) ? x : F[i](x - i); };
    G[i] = [&G, i](int x){ return (x < i) ? x : G[i](x - i); };
}

for (i = 10; i < n - 1; i++)
    cout << F[n - i](15) << "\t";
cout << endl;

for (i = 10; i < n - 1; i++)
    cout << G[n - i](15) << "\t";
cout << endl;

for (int i = 10; i < n - 1; i++)
    cout << F[n - i](15) << "\t";
cout << endl;

for (int i = 10; i < n - 1; i++)
    cout << G[n - i](15) << "\t";
cout << endl;

return 0;
}

1 个答案:

答案 0 :(得分:2)

如果要使用功能,则必须包含功能。 在#include <iostream>

之后添加关注行
#include <functional>