数组初始化需要括号括起的初始化列表lambda

Asi*_*taq 0 c++ lambda

我是lambda表达的新手,有点困惑为什么我在这里得到错误?

#include <iostream>
#include <algorithm>    
using namespace std;    
int main()
{
    int arr[] = { 11, 21, 4, 13 };

    for_each(arr, arr + 4, [arr](int x) {
        cout << x;
    });
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我只为这个功能添加了LAMBDA.

void fun1(int x)
    {
        cout << x << " ";
    }
Run Code Online (Sandbox Code Playgroud)

这是visual studio上的错误消息.

'main::<lambda_4ee0815d3a456ed46cc70a2a94c10f76>::arr': 
array initialization requires a brace-enclosed initializer list Project1
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 6

您无法复制数组,因此您可以arr通过引用进行捕获,而不是实际需要它:

for_each(arr, arr + 4, [&arr](int x) { cout << x; });
//                     ^^^
Run Code Online (Sandbox Code Playgroud)

但是,由于您没有引用lambda主体中的数组,因此根本不需要捕获它:

for_each(arr, arr + 4, [](int x) { cout << x; });
//                    ^^^^
Run Code Online (Sandbox Code Playgroud)