C++20 sections · 1024 units
Open in Course

find

Searching for values

I'll show you find(v.begin(), v.end(), target) to search for a value. It returns an iterator to the first match, or v.end() if not found. You'll check the result: if (find(v.begin(), v.end(), 42) != v.end()) means 42 exists.

Never dereference v.end() because it points past the last element. This runs in O(n)O(n) time. For sorted vectors, use binary_search() instead to get O(logn)O(\log n) performance.