Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::views::slide — sliding window view

C++23 std::views::slide creates a lazy view of consecutive, overlapping windows of length n. The windows refer to elements in the underlying range rather than forming separate containers. It requires at least a forward_range and n > 0.

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

Syntax

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

std::views::slide, available in <ranges> in C++23, is a range adaptor. Both std::views::slide(range, n) and range | std::views::slide(n) create a std::ranges::slide_view. Each result element is a view over n consecutive source elements; the next window starts one element later.

For a finite source of length L, the number of windows is max(L - n + 1, 0). There is no partial final window: if L < n, the result is empty. The width n can be determined at runtime, but it must satisfy the precondition n > 0; zero and negative values are not valid arguments. The underlying range must model forward_range, so a single-pass input range is insufficient.

Windows are produced lazily without copying elements into separate containers. For a mutable source, changing an element through a window changes the source, and overlapping windows can refer to the same element. When the source is an existing container passed as an lvalue, it must remain alive throughout use of the windows; also avoid operations that invalidate its iterators.

The example sums three windows of length 3: elements 1, 2, 3, then 2, 3, 4, and 3, 4, 5. Each window is traversed afresh—the adaptor does not calculate a rolling sum itself. The expected output is 6, 9, 12, each on its own line.

Examples

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

int main() {
    std::array<int, 5> values{1, 2, 3, 4, 5};
    for (auto window : values | std::views::slide(3)) {
        int sum = 0;
        for (int value : window) {
            sum += value;
        }
        std::cout << sum << '\n';
    }
}

Result

6
9
12

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