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::reduce

Use case

Parallel-friendly version of accumulate.

Explanation

Unlike accumulate, operation must be associative (grouping does not matter) and commutative (order does not matter) for correct parallel execution.

Time complexity: O(n), sequential. See std::reduce.

Code

#include <cstdint>
#include <numeric>
#include <print>
#include <vector>

int main() {
  std::vector<uint64_t> segmentSizes = {4096, 4096, 8192, 16384};

  uint64_t total = std::reduce(segmentSizes.begin(), segmentSizes.end());

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

  return 0;
}

View on GitHub.

Output

$ ./src/algorithms/build/std-reduce
Total size: 32768