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 add1vector<int> nums = {1, 2, 3, 4, 5};// Running total, starts at 02int sum = 0;// for_each calls the lambda for each element; [&sum] captures sum by reference so it can be changed3for_each(nums.begin(), nums.end(), [&sum](int n) { // Add the current element to the outer sum4 sum += n;5});// Print 1 + 2 + 3 + 4 + 5 = 156cout << sum << endl;Output
15
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