Home > Backend Development > C++ > body text

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

WBOY
Release: 2024-04-17 16:39:02
Original
839 people have browsed it

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;
};
Copy after login

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;
};
Copy after login

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

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template