Use lambdas for scoped reusable code
Lambda expressions can be defined and stored for later use. They can be passed as parameters, stored in data structures, and called in different contexts with different parameters. They are as flexible as functions, but with the mobility of data.
How to do it…
Let's start with a simple program that we'll use to test various configurations of lambda expressions:
- We'll first define a
main()
function and use it to experiment with lambdas:int main() { ... // code goes here }
- Inside the
main()
function, we'll declare a couple of lambdas. The basic definition of a lambda requires a pair of square brackets and a block of code in curly brackets:auto one = [](){ return "one"; }; auto two = []{ return "two"; };
Notice that the first example one
includes parentheses after the square brackets, and the second example two
does not. The empty parameter parentheses are...