c++c++20

What is the use of std::ranges::views::lazy_split when we have std::ranges::views::split?


C++20 introduced two range adapters for splitting sequences: std::ranges::views::split and std::ranges::views::lazy_split.

At first glance, views::split seems clearly superior:

In contrast, views::lazy_split has significant limitations:

Is there a practical scenario where lazy_split is actually better or preferred over split? Or is it mostly a legacy artifact after the design changes introduced by P2210R2?


Solution

  • Support for input_range is why lazy_split_view still has value over split_view, for example, you can split on istream_view or std::generator:

    std::istringstream is{"1 0 2 0 3"};
    auto r = std::views::istream<int>(is)
           | std::views::lazy_split(0);
    std::println("{}", r); // prints [[1], [2], [3]]
    

    In addition, although subranges split by lazy_split_view can only be forward_range at most, lazy_split_view does not compute them exactly (the lazy part) at each increment like split_view does, which makes its iterator relatively smaller than that of split_view as it does not need to store the subrange internally.