Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::views::chunk — divide a range into chunks

C++23 std::views::chunk creates a lazy range of views over successive, non-overlapping groups of n elements. The final chunk may be shorter; n must be positive.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <ranges>
std::views::chunk(range, n)
range | std::views::chunk(n)

std::views::chunk, available in <ranges> since C++23, is a range adaptor that creates a std::ranges::chunk_view. Writing std::views::chunk(range, n) corresponds to the pipeline form range | std::views::chunk(n). Elements retain their order; chunks do not overlap, and the last may contain fewer than n elements. An empty range produces no chunks.

The precondition is n > 0: do not pass zero or a negative value. The view forms chunks lazily without copying elements into separate containers. When the source is a container passed as an lvalue, it must remain alive while the view is used; operations invalidating its iterators also endanger chunk views.

The source must be adaptable to a view and satisfy at least input_range. For a single-pass source, chunks share traversal state: process the current chunk before advancing to the next. A source satisfying forward_range supports repeated traversal.

The example sums chunks {1, 2}, {3, 4}, and {5}, printing 3, 7, and 5 on separate lines. Selecting C++23 mode alone does not establish standard-library support or attest operation in a production runtime.

Examples

#include <array>
#include <iostream>
#include <ranges>

int main() {
    std::array<int, 5> values{1, 2, 3, 4, 5};

    for (auto chunk : values | std::views::chunk(2)) {
        int sum = 0;
        for (int value : chunk) {
            sum += value;
        }
        std::cout << sum << '\n';
    }
}

Result

3
7
5

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources