Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::views::take_while — a prefix satisfying a condition

std::views::take_while creates a lazy view of the initial range elements satisfying a predicate. It ends before the first element that fails the condition and does not resume searching for later matches.

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

Syntax

std::views::take_while(range, pred)
range | std::views::take_while(pred)

std::views::take_while is a range adaptor that creates a std::ranges::take_while_view. Use std::views::take_while(range, pred) or range | std::views::take_while(pred). The view includes consecutive elements from the beginning until the first false result, excluding the element that caused it. If the first element fails, the result is empty; if every element passes, it covers the entire range.

The view is lazy: constructing it does not build a separate result container. The condition is checked during iteration when comparing the iterator with the end sentinel. Do not assume exactly one predicate call per element or make the result depend on a call counter. The predicate must satisfy indirect_unary_predicate<const Pred, iterator_t<V>>, and the underlying view V must satisfy input_range.

In the example, x < 5 accepts 2 and 4; 7 ends the view. The later 1 and 3 are not included: this selects a prefix, not all matching elements. The array values must remain alive while the view referring to it is used.

For single-pass input such as a stream, identifying the stopping element may already read it from the source. Do not assume that it remains available for the next stream extraction.

Examples

#include <iostream>
#include <ranges>

int main() {
    int values[] = {2, 4, 7, 1, 3};
    auto prefix = values | std::views::take_while([](int x) {
        return x < 5;
    });

    bool first = true;
    for (int x : prefix) {
        if (!first) std::cout << ' ';
        std::cout << x;
        first = false;
    }
    std::cout << '\n';
}

Result

2 4

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