Lambda with capture in C++

Level 3130 keystrokes

[factor] copies the outer variable factor into the lambda, so it can be used inside. multiply(5) returns 15 and multiply(10) returns 30.

C++ code

// A local variable outside the lambda
1int factor = 3;
// [factor] captures a copy of factor by value; later changes to factor would not affect it
2auto multiply = [factor](int x) { return x * factor; };
// 5 * 3: prints 15
3cout << multiply(5) << endl;
// 10 * 3: prints 30
4cout << multiply(10) << endl;

Output

15
30
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 8
  • ;× 5
  • (× 3
  • )× 3
  • =× 2
  • [× 1
  • ]× 1
  • {× 1
  • }× 1
  • *× 1

More C++ examples at level 3

← C++ typing practice