20.12.2022 19:00 Joseph Hesse kirjutas:
> I want to sum an array of int's in a lambda function.
>
> In the following code, function f1 does this with no problem.
>
> In function f2, I am able to sum an int array using a range based
> for loop. That this works surprises me since the array name is not
> converted to a pointer and the for loop "looks around" to find the
> size of int x[].
>
> The commented out code in f2 was my attempt, as in f1, to
> put the code to sum the array in a lambda. It does not compile.
>
> Is it possible to make this work?
>
> Thank you,
> Joe
> =======================================================
> #include <iostream>
> #include <vector>
> using namespace std;
>
> void f2(){
> int x[4] = {1, 2, 3, 4};
>
> int sum = 0;
> for(const int &i : x)
> sum += i;
> cout << "sum = " << sum << '\n';
>
> /*
> auto fp = [] (int x[])
> {
> int sum = 0;
> for(const int &i : x)
> sum += i;
> return sum;
> };
>
> cout << "sum = " << fp(x) << '\n';
> */
> }
You can fix it easily by over-using auto:
void f2() {
int x[4] = { 1, 2, 3, 4 };
auto fp = [] (const auto& x)
{
int sum = 0;
for(const int &i : x)
sum += i;
return sum;
};
std::cout << "sum = " << fp(x) << '\n';
}
However, using C arrays seems fragile in general as they decay to
pointers too easily. This seems better:
void f2() {
std::array<int, 4> x = { 1, 2, 3, 4 };
auto fp = [] (const auto& range)
{
int sum = 0;
for(const int &i : range)
sum += i;
return sum;
};
std::cout << "sum = " << fp(x) << '\n';
}