Lambda expression in C++

Level 4134 keystrokes

Sums the elements of a vector with for_each and a lambda that captures sum by reference, then prints 15.

C++ code

// Vector of the numbers to add
1vector<int> nums = {1, 2, 3, 4, 5};
// Running total, starts at 0
2int sum = 0;
// for_each calls the lambda for each element; [&sum] captures sum by reference so it can be changed
3for_each(nums.begin(), nums.end(), [&sum](int n) {
// Add the current element to the outer sum
4 sum += n;
5});
// Print 1 + 2 + 3 + 4 + 5 = 15
6cout << sum << endl;

Output

15
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.

  • ,× 6
  • ;× 5
  • <× 5
  • (× 4
  • )× 4
  • =× 3
  • .× 2
  • {× 2
  • }× 2
  • _× 1

More C++ examples at level 4

← C++ typing practice