c++c++11valarray

What is the difference between the two snippets?


I need some explanation for [](int x){return x=x+5;}. What does [] (int x) mean?

I ran the varr.apply(incelemby5) where incelemby5 increases array elements by 5. Got the same results

varr1 = varr.apply([](int x){return x=x+5;});

int incelemby5(int x) {
    return x+5;
}

Solution

  • C++11 introduces Lambda expression. You can create a function object(which has operator()) immediately. Each lambda has a unique type name so that compiler can optimize it easier than the function pointer which is the same type name for the same signature.

    BTW, these two samples will make the same effects because x which is 1st argument of the lambda is not an lvalue reference.

    varr1 = varr.apply([](int x){return x=x+5;});
    
    varr1 = varr.apply([](int x){return x+5;});