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::ranges::fold_left

Use case

Accumulate with explicit direction.

Explanation

fold_left = std::accumulate for ranges. Also fold_right, fold_left_first (uses the first element as initial value).

Code

#include <algorithm>
#include <cstdint>
#include <print>
#include <vector>

int main() {
  std::vector<size_t> sectionSizes = {0x1000, 0x2000, 0x500, 0x800};

  auto total = std::ranges::fold_left(sectionSizes, 0uz, std::plus{});

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

  // https://en.wikipedia.org/wiki/Mach-O
  std::vector<uint8_t> data = {0xCF, 0xFA, 0xED, 0xFE};

  auto checksum = std::ranges::fold_left(data, uint8_t{0}, std::bit_xor{});

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

  return 0;
}

View on GitHub.

Output

$ ./src/c++23/build/std-ranges-fold_left
Total size: 0x3d00
Checksum: 0x26