WeCodeAcademy

C++ Lambdas and std::function

ExampleC++
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
using namespace std;

int main() {
  auto square = [](int x) { return x * x; };
  cout << square(7) << endl;

  int factor = 3;
  auto times = [factor](int x) { return x * factor; };   // capture by value
  cout << times(5) << endl;

  int total = 0;
  vector<int> v = {1, 2, 3, 4};
  for_each(v.begin(), v.end(), [&total](int x) { total += x; }); // capture by reference
  cout << total << endl;

  function<int(int)> fib = [&](int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); };
  cout << fib(10) << endl;

  sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
  for (int x : v) cout << x << " ";
  cout << endl;
  return 0;
}
Output
49
15
10
55
4 3 2 1

The brackets [ ] choose what the lambda captures from the surrounding code: [=] copies, [&] references, [x] one variable.

Quick check

What does [&total] capture?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.