std::binary_search (3)  Linux Manuals
std::binary_search: std::binary_search
NAME
std::binary_search  std::binary_search
Synopsis
Defined in header <algorithm>
template< class ForwardIt, class T > (until C++20)
bool binary_search( ForwardIt first, ForwardIt last, const T& value );
template< class ForwardIt, class T > (since C++20)
constexpr bool binary_search( ForwardIt first, ForwardIt last, const T& value ); (1)
template< class ForwardIt, class T, class Compare > (until C++20)
bool binary_search( ForwardIt first, ForwardIt last, const T& value, Compare comp ); (2)
template< class ForwardIt, class T, class Compare > (since C++20)
constexpr bool binary_search( ForwardIt first, ForwardIt last, const T& value, Compare comp );
Checks if an element equivalent to value appears within the range [first, last).
For std::binary_search to succeed, the range [first, last) must be at least partially ordered with respect to value, i.e. it must satisfy all of the following requirements:
* partitioned with respect to element < value or comp(element, value) (that is, all elements for which the expression is true precedes all elements for which the expression is false)
* partitioned with respect to !(value < element) or !comp(value, element)
* for all elements, if element < value or comp(element, value) is true then !(value < element) or !comp(value, element) is also true
A fullysorted range meets these criteria.
The first version uses operator< to compare the elements, the second version uses the given comparison function comp.
Parameters
first, last  the range of elements to examine
value  value to compare the elements to
comp  While the signature does not need to have const &, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) Type1 and Type2 regardless of value_category (thus, Type1 & is not allowed
Type requirements

ForwardIt must meet the requirements of LegacyForwardIterator.

Compare must meet the requirements of BinaryPredicate. it is not required to satisfy Compare
Return value
true if an element equal to value is found, false otherwise.
Complexity
The number of comparisons performed is logarithmic in the distance between first and last (At most log
2(last  first) + O(1) comparisons). However, for nonLegacyRandomAccessIterators, number of iterator increments is linear.
Possible implementation
First version
Second version
Example
// Run this code
Output:
Defect reports
The following behaviorchanging defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
LWG_270 C++98 Compare was required to be a strict weak ordering only a partitioning is needed; heterogeneous comparisons permitted
See also
equal_range (function template)