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{1, 2, 3, 4};
std::println("coll: {}", coll);
// compute (((100 + E1) + E2) + E3) + ... :
auto [pos1, res1] = std::ranges::fold_left_with_iter(coll, 100, std::plus{});
std::println("sum from left with init: {} (at end(): {})",
res1, pos1 == coll.end());
// compute ((E1 + E2) + E3) + ... :
auto [pos2, optRes2] = std::ranges::fold_left_first_with_iter(coll,
std::plus{});
if (optRes2) {
std::println("sum from left (no init): {} (at end(): {})",
*optRes2, pos2 == coll.end());
}
}