Skip to the content of the web site.

Binary search algorithms

These functions are found in the #include <algorithm> library.

These are functions that use a binary search to find a value or values in a sorted container.

bool std::binary_search( itr_t itr_first, itr_t itr_last, T const &value )

This function returns true if there is an entry on the range that equals the argument value.

This function, as well as all others, allow for a fourth optional argument that is of type bool predicate( T lhs, T rhs ) that returns true if the lhs argument is less than the rhs.

itr_t std::lower_bound( itr_t itr_first, itr_t itr_last, T const &value )
itr_t std::upper_bound( itr_t itr_first, itr_t itr_last, T const &value )
std::pair<itr_t, itr_t> std::equal_range( itr_t itr_first, itr_t itr_last, T const &value )

The first (lower_bound(...))returns an iterator to either the locaction of the first entry equal to value if one can be found, or the location where that value could hypothetically be inserted while maintaining sorted. The word "hypothetically" is used because if value is greater than the last entry, then itr_last will be returned, and this may equal end().

The second (lower_bound(...)) returns an iterator to the locaction of the first greater than value if one can be found or itr_last, otherwise.

Together, the iterators returned by lower_bound(...) and upper_bound(...) define a range that spans all entries equal to value.

The third (equal_range(...)) returns a std::pair of iterators equal to those returned by the two previous functions.

All three functions allow for a fourth optional argument that is of type bool predicate( T lhs, T rhs ) that returns true if the lhs argument is less than the rhs.

You can view examples at replit.com.