85. Use the right STL search algorithm

Summary

Search “just enough”—the right search may be STL (slower than light), but it’ll still be pretty fast: This Item applies to searching for a particular value in a range, or for the location where it would be if it were in the range. To search an unsorted range, use find/find_if or count/count_if. To search a sorted range, use lower_bound, upper_bound, equal_range, or (rarely) binary_search. (Despite its common name, binary_search is usually not the right choice.)

Discussion

For unsorted ranges, find/find_if and count/count_if can tell you in linear time whether and where, respectively, an element exists in a range. Note that find/find_if is typically more efficient because it can stop searching ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.