C++23’s New Fold Algorithms -- Sy Brand

This post explains the benefits of the new “rangified” algorithms, talks you through the new C++23 additions, and explores some of the design space for fold algorithms in C++.

C++23’s New Fold Algorithms

by Sy Brand

From the article:

C++20’s algorithms make several improvements to the old iterator-based ones. The most obvious is that they now can take a range instead of requiring you to pass iterator pairs. But they also allow passing a “projection function” to be called on elements of the range before being processed, and the use of C++20 concepts for constraining their interfaces more strictly defines what valid uses of these algorithms are. These changes allow you to make refactors like:

// C++17 algorithm
cat find_kitten(const std::vector<cat>& cats) {
    return *std::find_if(cats.begin(), cats.end(),
        [](cat const& c) { return c.age == 0; });
}

// C++20 algorithm
cat find_kitten(std::span<cat> cats) {
    return *std::ranges::find(cats, 0, &cat::age);
}

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.