Home  >  Article  >  Backend Development  >  How does a C++ lambda expression capture external variables?

How does a C++ lambda expression capture external variables?

WBOY
WBOYOriginal
2024-04-17 16:39:02771browse

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.

C++ lambda 表达式如何捕获外部变量?

C lambda expression: capturing external variables

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.

Method 1: Capture by value

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;
};

Method 2: Capture by reference

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;
};

Method 3: Capture by value and reference

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 是按引用捕获的
};

Practical case

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn