Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::accumulate

Use case

Compute sum or fold operation (combining all elements into a single value) over range.

Explanation

Takes initial value and optional binary operation. Strictly left-to-right evaluation (not parallelizable). Use std::reduce for parallel-friendly version.

Time complexity: O(n). Process each element exactly once. See possible implementation.

Code

#include <algorithm>
#include <numeric>
#include <print>
#include <vector>

int main() {
  std::vector<uint64_t> sectionSizes = {1024, 2048, 1024, 4096};

  auto total = std::accumulate(sectionSizes.begin(), sectionSizes.end(), 0);

  std::println("Total size: {}", total);

  std::vector<uint8_t> bytes = {0x01, 0x02, 0x03, 0x04};

  uint32_t checksum =
      std::accumulate(bytes.begin(), bytes.end(), 0, std::bit_xor{});

  std::println("Checksum: {:#x}", checksum);

  return 0;
}

View on GitHub.

Output

$ ./src/algorithms/build/std-accumulate
Total size: 8192
Checksum: 0x4