Skip links

C++23: Slicing with std::views::chunk

One of the common use cases in programming involves extracting fixed size chunks from a given sequence and operating on them. Not a big deal at all. As a C++ developer, I have coded this quite often and have wished that the language had a built-in function for this. Fortunately, C++23 gives us std::views::chunk to simplify and standardize this use case.

The following example shows how this is done.

Using the chunk function
Using the chunk function

In the above, we extract 3 elements at a time from the given vector and print them. Next, we chunk in terms of 4 elements at a time. Treating this collection as an array, we extract and print the elements at index 1. 

Here is the output.

Program output
Program output

It is important to understand that std::views::chunk is a “lazy adaptor”; no unnecessary allocation or copying is done until we evaluate the underlying range. This has a significant impact on efficiency.

In the following example, we generate an infinite sequence of integers and take only the first three chunks, where each chunk has 4 elements. 

Working with infinite sequence
Working with infinite sequence

Here is the program output:

The output
The output

The next example uses another useful range adaptor – “stride”. This was also introduced in C++23 and it produces a view of every “Nth” element of an underlying range. 

Combining "stride" and "chunk"
Combining “stride” and “chunk”

Notice how we are able to cleanly use the “pipe” operator for composing different functions – another elegant testimony for the evolution of C++ from its earlier days1

Here is the output for this example:

Program Output
Program Output

As the above examples demonstrate, “chunk” is a simple but useful function in the C++23 standard library.

I used compiler explorer for this experiment.

Have a great day!

Leave a comment