The following code example is taken from the book
C++23 - The Complete Guide
by Nicolai M. Josuttis,
Leanpub, 2026
The code is licensed under a
Creative Commons Attribution 4.0 International License.
// raw code
#include <print>
#include <vector>
#include <algorithm>
int main()
{
std::vector coll{100, 2, 3, 4};
std::println("coll: {}", coll);
// compute ((E1 - E2) - E3) - ... :
auto optDiff1 = std::ranges::fold_left_first(coll, std::minus{});
if (optDiff1) {
std::println("diffs from left: {}", *optDiff1);
}
// compute ... - (En-2 - (En-1 - En)) :
auto optDiff2 = std::ranges::fold_right_last(coll, std::minus{});
if (optDiff2) {
std::println("diffs from right: {}", *optDiff2);
}
// compute and use sum of empty collection:
coll.clear();
auto optDiff3 = std::ranges::fold_left_first(coll, std::plus{});
std::println("diffs of empty collection: {}", optDiff3.value_or(0));
}