Lamda func how to return array

lamda newb here

let's say i want to return the array (of ints) {0,4,9} with a lamda func

how it be done

i have tried:

1
2
[]{0,4,9}
[]{return {0,4,9}}



i want it cause i want to pass them to a function as an armutment
so instead of doing

1
2
int temp[] = {0,4,9};
my_func{temp};


i wanna do

 
my_fucn([]{return the array})
Last edited on
Your original post keeps changing! And I can't actually see why you would want to do this with a lambda function anyway: you might as well just declare the array in situ.

However ...

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <vector>
using namespace std;

int main()
{
   auto fn = [](){ return vector<int>{ 0, 4, 9 }; };
   for ( auto e : fn() ) cout << e << ' ';
}



You can also do the following ... but I don't recommend it.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main()
{
   auto fn = [](){ return new int[3]{ 0, 4, 9 }; };
   int *p = fn();
   for ( int i = 0; i < 3; i++ ) cout << p[i] << ' ';
   delete [] p;
}

Last edited on
> let's say i want to return the array (of ints) {0,4,9} with a lamda func
> how it be done

We can't return an array by value (it would decay to a pointer if we try to do it);
however we can return a reference to the array.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

template < typename CALLABLE > void foo( CALLABLE fn )
{
    std::cout << "foo: got the sequence [ " ;
    for( const auto& v : fn() ) std::cout << v << ' ' ;
    std::cout << "]\n" ;
}

int main()
{
    int a[] { 12, 34, 89, 42, 18, 96, 72 } ;
    foo( [&a] () -> auto& { return a ; } ) ; // [&a] : capture a by reference
                                             // -> auto& : return reference (to a)

    const double b[] { 1.23, 4.89, 4.21, 8.96, 7.25 } ;
    foo( [&b] () -> auto& { return b ; } ) ;
}

http://coliru.stacked-crooked.com/a/08a32d39c5cf494a
Topic archived. No new replies allowed.