Daily bit(e) C++ #124, Алгоритмы сворачивания C++23: ranges::fold_left, ranges::fold_left_first, ranges::fold_right, ranges::fold_right_last.

C++23 представил набор алгоритмов свертки с поддержкой диапазона для замены числового алгоритма std::accumulate.

В библиотеке предусмотрены как левые, так и правые складки: std::ranges::fold_left и std::ranges::fold_right.

А также варианты, использующие в качестве инициализаторов первый/последний элементы: std::ranges::fold_left_first и std::ranges::fold_right_last.

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

std::vector<int64_t> data{1,2,3,4,5,6};

// Left fold, with initial value.  
auto v = std::ranges::fold_left(data, 10, std::plus<>{});
// Unlike with std::accumulate, the result type is based
// on the invocation result of operation(init, elem).
// decltype(v) == int64_t, v == 31

// Right fold, using the last element as initializer.
auto w = std::ranges::fold_right_last(data, std::plus<>{});
// The result is a std::optional to accomodate empty ranges.
// decltype(w) == std::optional<int64_t>, w == 21

std::vector<int64_t> empty;
// Left fold, using the first element as initializer.
auto z = std::ranges::fold_left_first(empty, std::plus<>{});
// z.has_value() == false

Откройте пример в Compiler Explorer.