Learning Hub Search Ctrl K

Modern C++ › C++23

Ranges Additions in C++23

to<>, zip, enumerate, chunk and more.

Since C++23 intermediate #ranges#ranges-to#zip#enumerate#chunk#slide#join_with#fold_left#cartesian_product#generator

Explanation

C++20 introduced ranges and views but left obvious gaps. C++23 fills most of them.

Materializing: std::ranges::to<Container>(): convert any range into a container, ending a pipeline (| std::ranges::to<std::vector>()).

New views (in std::views):

View What it does
zip(a, b, ...) tuples of corresponding elements
zip_transform(f, a, b) apply f across elements in lockstep
enumerate(r) pairs of (index, element)
chunk(r, n) non-overlapping sub-ranges of size n
slide(r, n) overlapping windows of size n
adjacent<N> / pairwise N consecutive elements as a tuple
chunk_by(pred) split where pred(prev, next) is false
stride(r, n) every n-th element
join_with(delim) like join, with a separator
cartesian_product(a, b) all combinations
repeat(v) / repeat(v, n) repeat a value
as_const, as_rvalue read-only / move-out adaptors

New algorithms: std::ranges::fold_left, fold_right, fold_left_first (a proper accumulate for ranges), contains, contains_subrange, starts_with, ends_with, find_last, iota.

std::generator<T> (<generator>): the standard coroutine-based lazy range (the hand-written generator from Coroutines ready-made).

Example

#include <algorithm>
#include <generator>
#include <iostream>
#include <map>
#include <print>
#include <ranges>
#include <string>
#include <vector>

namespace rv = std::views;
namespace rg = std::ranges;

std::generator<int> evens(int limit) {                     // C++23 lazy sequence
    for (int i = 0; i < limit; i += 2) co_yield i;
}

int main() {
    std::vector<std::string> names{"Ann", "Bob", "Cy"};
    std::vector<int> ages{31, 25, 40};

    for (auto [n, a] : rv::zip(names, ages))               // lockstep iteration
        std::println("{} is {}", n, a);

    for (auto [i, n] : rv::enumerate(names))               // index + element
        std::println("{}: {}", i, n);

    std::vector<int> v{1, 2, 3, 4, 5, 6, 7};
    for (auto c : v | rv::chunk(3)) std::println("chunk {}", c);        // [1,2,3] [4,5,6] [7]
    for (auto w : v | rv::slide(3) | rv::take(2)) std::println("window {}", w);   // [1,2,3] [2,3,4]

    auto squares = v | rv::transform([](int x) { return x * x; })
                     | rg::to<std::vector>();              // materialize into a vector
    std::println("squares {}", squares);

    std::println("{}", rg::fold_left(v, 0, std::plus<>{}));   // 28

    auto csv = names | rv::join_with(std::string(", ")) | rg::to<std::string>();
    std::println("{}", csv);                               // Ann, Bob, Cy

    for (auto [a, b] : rv::cartesian_product(rv::iota(1, 3), rv::iota(1, 3)))
        std::print("({},{}) ", a, b);                      // (1,1) (1,2) (2,1) (2,2)
    std::println();

    std::map<std::string, int> m = rv::zip(names, ages) | rg::to<std::map>();   // zip -> map
    std::println("{}", m);

    for (int e : evens(10) | rv::drop(1)) std::print("{} ", e);   // 2 4 6 8
    std::println();
    std::println("{} {}", rg::contains(v, 4), rg::starts_with(v, std::vector{1, 2}));   // true true
    return 0;
}

Common pitfalls

  • chunk and slide over an input range (not forward) have restrictions, and slide yields overlapping views of the same data.
  • A view over a temporary container dangles, just as in C++20. rg::to copies, so it is the safe way to keep results.
  • rv::enumerate gives (index, reference): structured-bind with auto& if you want to modify.
  • std::generator allocates a coroutine frame and is single-pass: you can’t iterate it twice.
  • zip of ranges with different lengths stops at the shortest.
  • Compile times and error messages are heavy for long pipelines; split them into named steps.
  • Support: MSVC 19.34+ for most (enumerate/cartesian_product 19.37+), GCC 13-14, libc++ is partial. Check each feature.

Legacy vs modern

// C++98..17: index loop or manual iterators, and temporary containers
for (std::size_t i = 0; i < names.size(); ++i) std::cout << i << ": " << names[i] << "\n";
std::map<std::string,int> m;
for (std::size_t i = 0; i < names.size(); ++i) m[names[i]] = ages[i];
// C++23
for (auto [i, n] : rv::enumerate(names)) ...
auto m = rv::zip(names, ages) | rg::to<std::map>();

See Algorithms for accumulate, transform and the erase-remove idiom that these replace, and Ranges and Views for the C++20 foundation.

Exercises

1. Sum every second element of a vector<int> using views and a fold.
auto s = std::ranges::fold_left(v | std::views::stride(2), 0, std::plus<>{});