std::find
std::find scans a range for the first element that equals a value. std::find_if uses a predicate. Both are O(n) and return end when nothing matches. They need only input iterators.
Detailed Explanation
Linear search is the algorithm you write as a loop. std::find(first, last, value) is that loop, named. It compares with ==. std::find_if(first, last, pred) calls pred(*it) until it is true. find_if_not inverts. find_first_of looks for any element that also appears in a second range.
The return is an iterator. Compare it to last (or v.end()). Dereferencing end is undefined. C++23 std::ranges::find can return a borrowed iterator or a dangling sentinel if you passed a temporary range; prefer naming the container.
Because they need only input iterators, find works on list, vector, istream_iterator, and raw pointers. There is no magic: a million elements means a million comparisons in the worst case. If you do this often on the same data, sort and lower_bound, or put the data in an unordered_set.
std::find on a map is the wrong tool if you have the key: map::find is O(log n) on the key. std::find_if on a map can search by mapped value, which is O(n).
std::search finds a subsequence (a needle range inside a haystack). std::adjacent_find finds two equal neighbours. std::find_end finds the last subsequence. Know the names so you do not write them by hand.
Ranges projections: std::ranges::find(users, 3, &User::id) finds the first user with id == 3 without a lambda. That is the readable form in C++20.
Do not use find to check membership in a hot set of strings; use a hash set. Do use find for a one-off scan, for a small vector, and for a stream you cannot rewind.
Code Examples
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{4, 8, 15, 16, 23};
auto it = std::find(v.begin(), v.end(), 15);
if (it != v.end()) {
std::cout << (it - v.begin()) << '\n'; // prints: 2
}
auto odd = std::find_if(v.begin(), v.end(), [](int n) { return n % 2 == 1; });
std::cout << *odd << '\n'; // prints: 15
}#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct User { std::string name; int id; };
int main() {
std::vector<User> users{{"ada", 1}, {"al", 2}};
auto it = std::ranges::find(users, 2, &User::id);
std::cout << it->name << '\n'; // prints: al
}Common Gotchas
Forgetting to test `== end`
`*std::find(...)` is undefined on a miss.
`find` on a map by value is linear
`m.find(key)` is the logarithmic one. `std::find_if` walks nodes.
`vector<bool>` proxies
`find` still works; taking `&*it` does not.
Predicates with state
a `find_if` predicate that increments a counter is fine; one that mutates the element makes the algorithm's complexity claims and "does not modify" notes invalid.