Skip to content

C++ Syntax Cheatsheet

Using Lambdas in C++

Structure of a lambda in C++

cpp
auto func = [<capture_clause>] (<arguments>) {
	// ...lambda body
};
auto func = [<capture_clause>] (<arguments>) {
	// ...lambda body
};

Capture Clause. A lambda expression begins with a capture clause, which captures variables from its envrionment for use in the lambda expression. A capture clause is specified with [] and should specify the variables being used in the lambda.

There are three specific wildcard types that are useful when specifying capture clauses.

  1. [] means the lambda doesn't take any variables from its environment.
  2. [=] means that all variables that are used are captured by value.
  3. [&] means that all variables that are used are captured by reference.

For example, all of the below capture clauses are equivalent.

cpp
[&variable1, variable2]
[&, variable2]
[=, &variable1]
[&variable1, variable2]
[&, variable2]
[=, &variable1]

for Loops

cpp
vector<int> v = {1, 2, 3, 4};

// Option 1: Index-based for loop
for (auto i = 0; i < v.size(), i++) {
  // ...
}

// Option 2: Range-based for loop
for (auto item : v) {
  // ...
}
vector<int> v = {1, 2, 3, 4};

// Option 1: Index-based for loop
for (auto i = 0; i < v.size(), i++) {
  // ...
}

// Option 2: Range-based for loop
for (auto item : v) {
  // ...
}