CKTIS / C++
std::find: first equal value in a range
std::find searches [first, last) from the beginning and returns the first iterator for which *i == value, or last.
Version: C++23
Syntax
template<class InputIterator, class T>
constexpr InputIterator std::find(
InputIterator first, InputIterator last, const T& value);
template<class ExecutionPolicy, class ForwardIterator, class T>
ForwardIterator std::find(ExecutionPolicy&& exec,
ForwardIterator first, ForwardIterator last, const T& value);std::find(first, last, value) from <algorithm> examines a half-open range and returns the first iterator i for which *i == value is true; it returns last when no match exists. The no-policy overload accepts an input iterator and is constexpr; the execution-policy overload requires a forward iterator.
The example finds 7 at index 2 and obtains the end iterator for missing 9, so it prints 2 1. An empty range immediately returns last. A result equal to last must not be dereferenced; a found iterator follows the container’s ordinary iterator-validity rules.
The range must be valid and *i == value must be well-formed and boolean-testable. The algorithm performs at most N comparisons for N elements; descriptive last - first does not require iterator subtraction. Without a policy, a comparison exception propagates. With any standard execution policy, an uncaught element-operation exception calls std::terminate, while failure to obtain temporary parallelization memory can throw std::bad_alloc.
Examples
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
int main() {
const std::array values{4, 8, 7, 3};
const auto found = std::find(values.begin(), values.end(), 7);
const auto missing = std::find(values.begin(), values.end(), 9);
std::cout << std::distance(values.begin(), found) << ' '
<< (missing == values.end()) << '\n';
}
Result
2 1
std::find → 2 1