std::find_if / std::ranges::find_if
Prev: std::sort | Up: algorithm_and_ranges | Next: std::transform
Rel: Lambdas, std::ranges & std::views
Ref: cppreference — std::ranges::find_if
Tags: #public #prog #cpp #stdlib #algorithms #tier/core
Overview
std::ranges::find_if (<algorithm>) searches linearly for the first element satisfying a predicate and returns an iterator to it (or range.end() if none matches).
Notes & Pitfalls
- Always compare the returned iterator against
.end()before dereferencing—dereferencing.end()is undefined behavior. - C++20
std::ranges::find_if(vec, pred)avoids passingbegin/endpairs manually.
Example
#include <algorithm>
#include <cassert>
#include <vector>
int main() {
std::vector<int> nums{1, 3, 8, 5};
auto it = std::find_if(nums.begin(), nums.end(), [](int n) { return n % 2 == 0; });
assert(it != nums.end() && *it == 8);
}
Linked from
Related notes
- tuts/cpp/stdlib/algorithm_and_ranges/sort Linked here; links to this page; shared tags: #algorithms, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/transform Linked here; links to this page; shared tags: #algorithms, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges Linked here; links to this page; shared tags: #algorithms, #cpp, #prog, #stdlib
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views Linked here; shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/builtins/lambdas Linked here; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/concurrency/atomic shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/jthread shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/mutex_and_lock_guard shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/thread shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/array shared tags: #cpp, #prog, #stdlib, #tier