1

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;
}
John Kugelman
  • 307,513
  • 65
  • 473
  • 519
adi_226
  • 41
  • 7
  • 1
    That's a "lambda", a way to define and pass a function to an object that will call it. – Ripi2 Oct 12 '19 at 01:27
  • 1
    Helpful reading: [What is a lambda expression in C++11?](https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11) – user4581301 Oct 12 '19 at 01:32

1 Answers1

3

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;});
yumetodo
  • 913
  • 6
  • 18