C++20 sections · 1024 units
Open in Course

Iterator Safety

Proper usage

I'll show you how algorithms return iterators that you must check before using. The find() function returns v.end() when the target isn't found, and dereferencing that crashes. Always compare before dereferencing: auto it = find(v.begin(), v.end(), x); if (it != v.end()) use(*it); protects against accessing invalid memory locations.

The same applies to lower_bound, upper_bound, min_element, and max_element. Check validity by comparing to end() before accessing the value through the iterator.