C++20: How to split range by size?

I want to split range {1, 2, 3, 4, 5} to range of subranges of <any size> (e.g with size of 2: {{1, 2}, {3, 4}, {5}}). Yet std::views::split only splits by delimiter.

Is there no standard “reverse join” or something to do this?

Answer

range-v3 calls this algorithm chunk. There is no such range adapter in C++20, but it is part of the set being proposed for C++23 under the same name. For example:

#include <vector>
#include <range/v3/view/chunk.hpp>
#include <fmt/format.h>
#include <fmt/ranges.h>

int main() {
    std::vector v = {1, 2, 3, 4, 5};
    fmt::print("{}n", v | ranges::views::chunk(2)); // prints {{1, 2}, {3, 4}, {5}}
}

This seems to be a pretty consistent choice of name for this algorithm across languages. Python has chunked, Rust has chunks, Swift has chunks(ofCount: n), D has chunks, etc.