Daily bit(e) of C++ | std::view::chunk

Šimon Tóth
2 min readJun 19, 2024

--

Daily bit(e) of C++ ♻️108, The C++23 view producing a range of “chunks”, i.e. sub-ranges with the specified number of elements each: std::views::chunk.

The C++23 std::views::chunk produces a view of sub-ranges spanning the provided number of elements each.

If the source range cannot be divided without a remainder, the last element in the range will be a shorter subrange that contains the remainder of the elements.

The view works for input ranges and will provide additional features based on the type of the underlying range (e.g. operator[] is provided if the underlying range is random access).

#include <vector>
#include <ranges>
#include <iostream>
#include <utility>

std::vector<int> data{1,2,3,4,5,6,7,8,9};

// Iterate over chunks of size 4 (and one chunk of size 1)
for (const auto& chunk : data | std::views::chunk(4)) {}
/* iterate over:
{1,2,3,4}
{5,6,7,8}
{9}
*/

auto view = data | std::views::chunk(4);
auto second = view[1]; // OK
// operator[] provided if source range is random access
// second == {5,6,7,8}

auto last = view.back(); // OK
// back() provided if source range is bidirectional
// last == {9}

std::vector<int> cube(27,0);
// Can be used to iterate multi-dimensional data stored as 1D
for (const auto &slice : cube | std::views::chunk(3*3)) {
// iterate over 3x3 slices
for (const auto &row : slice | std::views::chunk(3)) {
// iterate over lines of 3 elements
}
}

Open the example in Compiler Explorer.

--

--

Šimon Tóth

20 years worth of Software Engineering experience distilled into easily digestible articles.