STL accumulate in C++

Level 4216 keystrokes

Uses accumulate to compute the sum of a vector and, with a multiplying lambda and a start value of 1, its product, then prints 15 120.

C++ code

1vector<int> nums = {1, 2, 3, 4, 5};
// Add every element to the start value 0: 15
2int sum = accumulate(nums.begin(), nums.end(), 0);
// For a product the start value must be 1, not 0
3int product = accumulate(nums.begin(), nums.end(), 1,
// The lambda replaces + with *: 1*1*2*3*4*5 = 120
4 [](int a, int b) { return a * b; });
// Print 15 120
5cout << sum << " " << product << endl;

Output

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

  • ,× 10
  • <× 9
  • (× 7
  • )× 7
  • ;× 5
  • .× 4
  • =× 3
  • "× 2
  • {× 2
  • }× 2

More C++ examples at level 4

← C++ typing practice