std::binary_search

Header: <algorithm>

Checks if an element equivalent to value appears within the partitioned range [first,last).

# Declarations

template< class ForwardIt, class T >
bool binary_search( ForwardIt first, ForwardIt last,
const T& value );

(constexpr since C++20) (until C++26)

template< class ForwardIt, class T = typename std::iterator_traits
<ForwardIt>::value_type >
constexpr bool binary_search( ForwardIt first, ForwardIt last,
const T& value );

(since C++26)

template< class ForwardIt, class T, class Compare >
bool binary_search( ForwardIt first, ForwardIt last,
const T& value, Compare comp );

(constexpr since C++20) (until C++26)

template< class ForwardIt, class T = typename std::iterator_traits
<ForwardIt>::value_type,
class Compare >
constexpr bool binary_search( ForwardIt first, ForwardIt last,
const T& value, Compare comp );

(since C++26)

# Parameters

# Return value

true if an element equivalent to value is found, false otherwise.

# Notes

Although std::binary_search only requires [first,last) to be partitioned, this algorithm is usually used in the case where [first,last) is sorted, so that the binary search is valid for any value.

std::binary_search only checks whether an equivalent element exists. To obtain an iterator to that element (if exists), std::lower_bound should be used instead.

# Example

#include <algorithm>
#include <cassert>
#include <complex>
#include <iostream>
#include <vector>
 
int main()
{
    const auto haystack = {1, 3, 4, 5, 9};
 
    for (const auto needle : {1, 2, 3})
    {
        std::cout << "Searching for " << needle << '\n';
        if (std::binary_search(haystack.begin(), haystack.end(), needle))
            std::cout << "Found " << needle << '\n';
        else
            std::cout << "Not found!\n";
    }
 
    using CD = std::complex<double>;
    std::vector<CD> nums{{1, 1}, {2, 3}, {4, 2}, {4, 3}};
    auto cmpz = [](CD x, CD y){ return abs(x) < abs(y); };
    #ifdef __cpp_lib_algorithm_default_value_type
        assert(std::binary_search(nums.cbegin(), nums.cend(), {4, 2}, cmpz));
    #else
        assert(std::binary_search(nums.cbegin(), nums.cend(), CD{4, 2}, cmpz));
    #endif
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 270C++98Compare was required to satisfy Compare and T was requiredto be LessThanComparable (strict weak ordering required)only a partitioning is required;heterogeneous comparisons permitted
LWG 787C++98at most (\scriptsize \log_{2}(N)+2)log2(N)+2 comparisons were allowedcorrected to (\scriptsize \log_{2}(N)+O(1))log2(N)+O(1)

# See also