Daily bit(e) of C++ #89, The C++23 view that chunks the data based on the given binary predicate The C++23 std::views::chunk_by is a view similar to C++20 std::views::split; however, unlike split, it operates using a binary predicate. A new chunk will be started between the two tested elements when the predicate returns false. #include <ranges>
#include <vector>
#include <cmath>
std::vector<int> data{1,2,-4,-2,-1,8,7,3,4,-5,-5};
auto same_sign = [](int left, int right){
return std::signbit(left) == std::signbit(right);
};
for (const auto& chunk : data | std::views::chunk_by(same_sign)) {
// Iterate over chunks:
// {1,2}, {-4,-2,-1}, {8,7,3,4}, {-5,-5}
}