Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Algorithms

C++23 range additions: zip, enumerate, chunk and more

Reference for the C++23 range views zip, enumerate, chunk, slide, stride, join_with, cartesian_product, adjacent and pairwise, plus ranges::fold_left and to.

C++20 gave us the view machinery (filter, transform, take, ...). C++23 filled the most obvious gaps: iterating two sequences together (zip), getting an index next to each element (enumerate), cutting a sequence into pieces (chunk, slide, stride), pairing neighbors (pairwise, adjacent), flattening with a separator (join_with), and combining all pairs (cartesian_product). Next to them come new algorithms (ranges::fold_left, contains, starts_with, find_last) and the conversion std::ranges::to.

All of them are lazy, composable views like the ones in Range views. They live in <ranges> (algorithms in <algorithm>) and need -std=c++23, which our runner uses. GCC 15 supports nearly everything on this page; the one exception we found on our runner is ranges::starts_with / ranges::ends_with, which are in the standard but not yet in GCC 15's library (the examples avoid them).

C++
for (auto [name, score] : std::views::zip(names, scores)) { /* ... */ }
for (auto [i, x] : v | std::views::enumerate) { /* i is the index */ }
auto windows = v | std::views::slide(3);

Try it

C++ zip, enumerate and cartesian_product

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ chunk, slide, stride, pairwise and join_with

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
std::views::zip(r1, r2, ...)                  std::views::zip_transform(f, r1, r2, ...)
std::views::enumerate(r)                      // elements are tuple<index, reference>
std::views::chunk(n)       std::views::slide(n)       std::views::stride(n)
std::views::pairwise       std::views::adjacent<N>    std::views::adjacent_transform<N>(f)
std::views::cartesian_product(r1, r2, ...)
std::views::join_with(delim)                  std::views::as_const   std::views::as_rvalue
std::views::chunk_by(pred)                    std::views::repeat(x [, n])
std::ranges::to<Container>(range)             // see the std::ranges::to page
std::ranges::fold_left(r, init, f)    std::ranges::fold_right(r, init, f)
std::ranges::contains(r, v)   std::ranges::contains_subrange(r, sub)
std::ranges::find_last(r, v)    std::ranges::starts_with(r, p)   std::ranges::ends_with(r, p)
Name Description
n Chunk, window or stride size. Must be greater than zero (a zero is undefined behavior).
r1, r2, ... The ranges to combine. zip stops when the shortest one ends.
delim An element or a range placed between joined pieces.
f A callable receiving one element from each range, or the accumulator and the next element for folds.
init Starting value of a fold.

Returns: views (lazy) for the views:: adaptors, with tuple-like elements for zip, enumerate, pairwise, adjacent and cartesian_product. fold_left returns the final value; contains, starts_with and ends_with return bool; find_last returns the subrange from the last match to the end.

Errors / undefined behavior: chunk(0), slide(0) and stride(0) are undefined. Using a view after its container is gone is undefined, as for all views.

Usage notes

  • Structured bindings. Elements of zip and enumerate are tuples, so auto [a, b] works. They hold references when the source ranges yield references, so writing to the binding writes to the container (if the container is non-const).
  • enumerate index type is the range's difference type (a signed integer), which is why the example casts it.
  • slide versus chunk. chunk(3) over 7 elements gives pieces of 3, 3 and 1. slide(3) gives 5 overlapping windows of 3. If the range is shorter than the window, slide yields nothing.
  • Stability of the order. cartesian_product iterates the last range fastest, like nested loops with the first range outermost.
  • Not every adaptor is const-iterable. chunk_by, slide over some ranges and join_with may need a non-const view. Iterate with auto&& in generic code.
  • Library support. Every view and algorithm in the examples compiles with GCC 15 in -std=c++23 mode, except std::ranges::starts_with and std::ranges::ends_with, which GCC 15.2 does not provide yet (use std::ranges::equal with std::views::take, or std::string_view::starts_with). Older standard libraries lack more: most of these views need GCC 13 to 15 depending on the view, so check your library version.
  • fold_left is the ranges replacement for std::accumulate. Unlike accumulate, the accumulator type is deduced from what f returns, so fold_left(doubles, 0, std::plus<>{}) sums as double instead of truncating to int. fold_left_first takes no initial value and returns an std::optional.
  • as_const and as_rvalue (C++23) turn the elements into const references or rvalue references, the latter to move strings out of a vector into another container.
  • repeat produces the same value n times, or forever with a single argument; combine with take.