# 使用 Lambda、函式物件和限制函式

Visual Studio 2015

```
void CpuMethod() {

int aCPP[] = {1, 2, 3, 4, 5};
int bCPP[] = {6, 7, 8, 9, 10};
int sumCPP[5];

for (int idx = 0; idx < 5; idx++)
{
sumCPP[idx] = aCPP[idx] + bCPP[idx];
}

for (int idx = 0; idx < 5; idx++)
{
std::cout << sumCPP[idx] << "\n";
}
}

```

## Lambda 運算式

```
int aCPP[] = {1, 2, 3, 4, 5};
int bCPP[] = {6, 7, 8, 9, 10};
int sumCPP[5];

array_view<const int, 1> a(5, aCPP);
array_view<const int, 1> b(5, bCPP);
array_view<int, 1> sum(5, sumCPP);

parallel_for_each(
sum.extent,
[=](index<1> idx) restrict(amp)
{
sum[idx] = a[idx] + b[idx];
}
);

for (int i = 0; i < 5; i++) {
std::cout << sum[i] << "\n";
}
}

```

Lambda 運算式必須包含一個索引參數，而且必須包含`restrict(amp)`。 在範例中，array_view `sum` 物件排名為 1。 因此， lambda 陳述式的參數是排序為 1 的索引物件 。 在執行階段，lambda 運算式會對 array_view 物件中的每個項目執行一次。 如需詳細資訊，請參閱Lambda 運算式語法

## Function 物件

```
{
public:
const array_view<int, 1>& b,
const array_view<int, 1>& sum
)
: a(a), b(b), sum(sum)
{
}

void operator()(index<1> idx) restrict(amp)
{
sum[idx] = a[idx] + b[idx];
}

private:
array_view<int, 1> a;
array_view<int, 1> b;
array_view<int, 1> sum;
};

int aCPP[] = {1, 2, 3, 4, 5};
int bCPP[] = {6, 7, 8, 9, 10};
int sumCPP[5];

array_view<const int, 1> a(5, aCPP);
array_view<const int, 1> b(5, bCPP);
array_view<int, 1> sum(5, sumCPP);

parallel_for_each(
sum.extent,
);

for (int i = 0; i < 5; i++) {
std::cout << sum[i] << "\n";
}
}

```

## C++ AMP 限制函式

```
void AddElementsWithRestrictedFunction(index<1> idx, array_view<int, 1> sum, array_view<int, 1> a, array_view<int, 1> b) restrict(amp)
{
sum[idx] = a[idx] + b[idx];
}

int aCPP[] = {1, 2, 3, 4, 5};
int bCPP[] = {6, 7, 8, 9, 10};
int sumCPP[5];

array_view<int, 1> a(5, aCPP);
array_view<int, 1> b(5, bCPP);
array_view<int, 1> sum(5, sumCPP);

parallel_for_each(
sum.extent,
[=](index<1> idx) restrict(amp)
{
}
);

for (int i = 0; i < 5; i++) {
std::cout << sum[i] << "\n";
}
}

```