I am trying to pass an array to a lambda expression, where I want to print it out. I don't understand how to pass the array into the function. The problem seems to be rooted at the conversion of the array when it is passed to the lambda function. This is the current state of the function:
int actual_array[5] = {7,8,9,2,1};
const int actual_i = 3;
auto print_array = [](int &array, int i) -> int {
//print out array
return 0;
}(&actual_array, actual_i);
You can't pass an array by value, and your syntax for passing a pointer is all wrong.
It's actually easy to pass a pointer or reference to an array though. With generic lambdas you can ignore the fact that the dimension is part of the type and just simply write:
#include <iostream>
int main()
{
int actual_array[5] = {7,8,9,2,1};
const int actual_i = 3;
auto print_array = [](auto& ar, int i) {
std::cout << ar[i] << '\n';
};
print_array(actual_array, actual_i);
}
In this example, the print_array instantiation that you call is accepting a int(&)[5], hidden behind the auto&.
If you can't abide by the generic lambda (which is basically a template) for some reason, then go old-school:
#include <iostream>
int main()
{
int actual_array[5] = {7,8,9,2,1};
const int actual_i = 3;
auto print_array = [](const int* ar, int i) {
std::cout << ar[i] << '\n';
};
print_array(&actual_array[0], actual_i);
}
None of this is specific to lambdas. It's the same for any function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With