Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lambda Functions | Some Advanced Topics
C++ Functions
course content

Conteúdo do Curso

C++ Functions

C++ Functions

1. Introduction
2. Function Arguments Specification
3. Function Return Values Specification
4. Some Advanced Topics

Lambda Functions

Lambda functions, or anonymous functions, are a feature that allows you to create small, unnamed functions inline in your code. They are particularly useful when you need a simple function for a short period of time and don't want to define a separate named function.

Lambda functions are useful for several reasons:

  1. Conciseness: Lambda functions allow you to write short and concise code. They are ideal for operations that can be expressed in a few lines.
  2. Local Scope: They can capture variables from the surrounding scope, allowing you to use variables from the parent function within the lambda.
  3. Flexibility: Lambdas can be passed as arguments to other functions, making them handy for functions like std::for_each, std::sort, etc.

How to create a lambda function?

We can use the following syntax to create lambda function:

A capture clause in a lambda function allows you to specify which variables from the surrounding scope (outside the lambda function) can be accessed and used within the lambda function. There are 3 commonly types of capture clauses:

  • Capture Nothing []: The lambda function cannot access any variables from the surrounding scope.
  • Capture Specific Variables by Value [var1, var2, ...]: The lambda function can access specific variables from the surrounding scope by value.
  • Capture Specific Variables by Reference [&var1, &var2, ...]: The lambda function can access specific variables from the surrounding scope by reference.
cpp

main

copy
12345678910111213
#include <iostream> int main() { int multiplier = 2; // Lambda function capturing 'multiplier' by reference and with explicit return type (int) int result = [&multiplier](int num) -> int { return num * num * multiplier; }(5); // Invoking the lambda with argument 5 std::cout << "Result: " << result << std::endl; }

The function is constructed as follows:

  • The lambda function captures multiplier variable by reference [&multiplier].
  • The return type -> int specifies that the lambda function returns an integer.
  • The lambda is immediately invoked with the argument 5, and the result is stored in the result variable.

What is the purpose of a capture clause in a lambda function?

Selecione a resposta correta

Tudo estava claro?

Seção 4. Capítulo 4
We're sorry to hear that something went wrong. What happened?
some-alt