Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::ranges::find — first match in a range

`std::ranges::find` locates the first element equal to a supplied value, optionally after projection. The result is not a `bool`: an iterator points to the first match or marks the end if there is no match. The range overload instead returns `std::ranges::dangling` when passed an rvalue range that does not satisfy `borrowed_range`.

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

Syntax

#include <algorithm>
std::ranges::find(r, value)
std::ranges::find(r, value, proj)
std::ranges::find(first, last, value)
std::ranges::find(first, last, value, proj)

std::ranges::find, declared in <algorithm>, accepts a range or an iterator–sentinel pair; their types may differ. It requires at least an input iterator and a valid equality comparison. It tests std::invoke(proj, *i) == value; the default projection leaves the element unchanged. A projection can select a field, for example. For a custom condition, you can pass a predicate directly to std::ranges::find_if or use a projection that returns bool and search for true with std::ranges::find.

It returns an iterator to the first match or an end iterator. Compare the result with the range end before dereferencing. For N elements, it performs at most N comparisons and projection applications: complexity is linear.

The range overload returns std::ranges::borrowed_iterator_t<R>. For a temporary range that does not satisfy borrowed_range, the result is std::ranges::dangling, not a usable iterator. An ordinary iterator still depends on the data's lifetime and invalidation rules.

The example selects Item::id, but the result points to the whole Item: the first 7 yields 12, and the missing 5 yields true. This entry targets C++23; the current source draft also contains later extensions.

Examples

#include <algorithm>
#include <array>
#include <iostream>

struct Item {
    int id;
    int stock;
};

int main() {
    const std::array<Item, 3> items{{{7, 12}, {9, 4}, {7, 99}}};
    const auto found = std::ranges::find(items, 7, &Item::id);
    if (found != items.end()) {
        std::cout << found->stock << '\n';
    }

    const auto missing = std::ranges::find(items, 5, &Item::id);
    std::cout << std::boolalpha << (missing == items.end()) << '\n';
}

Result

12
true

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