There are three ways to capture lambda expressions of external variables in C: Capture by value: Create a copy of the variable. Capture by reference: Get a variable reference. Capture by value and reference simultaneously: Allows capturing of multiple variables, either by value or by reference.
Lambda expression is a powerful tool in C that allows us to define anonymous functions within functions. Sometimes, we need to access external variables in lambda expressions. This tutorial will cover a few different ways to capture external variables.
Using the [var]
syntax, we can capture the variable var
by value. This means that the lambda expression will create a copy of the variable.
auto var = 10; auto lambda = [var] { // 这里可以使用 var return var; };
Using the [&var]
syntax, we can capture the variable var
by reference. This means that the lambda expression will get a reference to the variable.
auto var = 10; auto lambda = [&var] { // 这里可以使用 var 并修改它 var++; return var; };
We can capture multiple variables by value and reference at the same time. For example, the following lambda expression captures val
by value and ref
by reference:
auto func = [](int val, int& ref) { // val 是按值捕获的,ref 是按引用捕获的 };
The following example shows how to use Capturing external variables by value and by reference:
#include <iostream> #include <vector> using namespace std; int main() { // 按值捕获 int num = 10; auto lambda1 = [num] { return num++; }; cout << lambda1() << endl; // 输出 10 // 按引用捕获 vector<int> myVector{1, 2, 3}; auto lambda2 = [&myVector] { myVector.push_back(4); }; lambda2(); for (auto& elem : myVector) { cout << elem << " "; // 输出 1 2 3 4 } cout << endl; return 0; }
The above is the detailed content of How does a C++ lambda expression capture external variables?. For more information, please follow other related articles on the PHP Chinese website!