Anonymous Function
Anonymous functions don’t have names. I first learned about this at Marianopolis College programming class, but it was actually super easy.
I wonder if every single person in that class went into Software Engineering / Computer Science lol.
Python
Don’t know if this is the perfect syntax for it.
a = lambda x: x+2
C++
Used for the first time when I was trying to write ORB-SLAM from scratch.
To access local variables from within anonymous function, you need a Closure.
float tot = std::accumulate(weights.begin(), weights.end(), 0);
std::transform(weights.begin(), weights.end(), [tot](float x)->float{return(x/tot);});
In this case tot
is captured by value. C++11 lambdas support capturing by:
- value
[x]
- reference
[&x]
- any variable currently in scope by reference
[&]
- same as 3, but by value
[=]
You can mix any of the above in a comma separated list [x, &y]
.
Tip
Using the third way
[&]
is generally considered bad practice, because you aren’t explicit about the variables that you want to use.