Anonymous Functions in C++
Lesson Introduction
Why use anonymous functions in C++? Anonymous functions, known as lambda expressions, help write concise, readable code. They are defined inline without needing a separate function declaration. They're especially useful for short snippets as arguments to algorithms or event handlers.
By the end of this lesson, you'll understand what anonymous functions (lambda expressions) are, how to create them, and how they can simplify your code.
Introduction to Anonymous Functions
Anonymous functions in C++ are functions defined without a name, commonly called lambda expressions. The basic syntax of a lambda expression is:
- Capture: Specifies which outside variables are accessible in the lambda.
- Parameters: Function parameters.
- Body: The actual code to execute.
Simple Example of Anonymous Functions
Consider the following code snippet where we use a lambda function to print elements of a vector. We will put the lambda function into a variable and use it later.
Here, print_number is a variable that stores the lambda function that takes an integer n and prints it. This lambda is used in a for loop to print each number in the numbers vector.
Capturing Variables in Lambda
Sometimes, we must access variables from the surrounding scope within your lambda. This is done using the capture clause:
Here, multiply_by_factor is a lambda capturing the factor variable by value. It multiplies each element of the numbers vector by factor.
