std::binary_search - cppreference.com

From cppreference.com

Defined in header

<algorithm>

template<classForwardIt,classT>boolbinary_search(ForwardItfirst,ForwardItlast,constT&value); (1)(constexpr since C++20)
(until C++26)template<classForwardIt,classT=typenamestd::iterator_traits<ForwardIt>::value_type>constexprboolbinary_search(ForwardItfirst,ForwardItlast,constT&value);(since C++26)template<classForwardIt,classT,classCompare>boolbinary_search(ForwardItfirst,ForwardItlast,constT&value,Comparecomp); (2)(constexpr since C++20)
(until C++26)template<classForwardIt,classT=typenamestd::iterator_traits<ForwardIt>::value_type,classCompare>constexprboolbinary_search(ForwardItfirst,ForwardItlast,constT&value,Comparecomp);(since C++26)Checks if an element equivalent to value exists in the partitioned source range [first, last). An element is considered equivalent to value if it neither orders before nor orders after value.

1) The order is determined by operator<(until C++20)std::less{}(since C++20).

Given two expressions bool(e<value) and !bool(value<e)(until C++20)bool(std::less{}(e,value)) and !bool(std::less{}(value,e))(since C++20). If any of the following conditions is satisfied, the behavior is undefined:

The elements e of the source range are not

partitioned

with respect to these two expressions at the same time.

There exists an element e in the source range such that these two expressions yield different values.

2) The order is determined by comp.

Given two expressions bool(comp(e,value)) and !bool(comp(value,e)). If any of the following conditions is satisfied, the behavior is undefined:

The elements e of the source range are not partitioned with respect to these two expressions at the same time.

There exists an element e in the source range such that these two expressions yield different values.

Parameters

first, last - the pair of iterators defining the source

range

value - value to compare the elements to comp - binary predicate which returns ​true if the first argument is ordered before the second. The signature of the predicate function should be equivalent to the following:

boolpred(constType1&a,constType2&b);

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, nor is Type1 unless for Type1 a move is equivalent to a copy(since C++11)).
The type Type1 must be such that an object of type ForwardIt can be dereferenced and then implicitly converted to Type1. The type Type2 must be such that an object of type T can be implicitly converted to Type2. ​

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 equivalent to value exists, false otherwise.

Complexity

Given N as std::distance(first,last):

1) At most log2(N)+𝓞(1) comparisons with value using operator<(until C++20)std::less{}(since C++20).

2) At most log2(N)+𝓞(1) applications of the comparator comp.

Notes

Although std::binary_search only requires the source range to be partitioned, this algorithm is usually used in the case where the source range 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.

If ForwardIt is not a

LegacyRandomAccessIterator

, the number of iterator increments is linear in std::distance(first,last).

Feature-test

macroValueStdFeature

__cpp_lib_algorithm_default_value_type

202403

(C++26)

List-initialization

for algorithms (

1,2

)Possible implementation

See also the implementations in

libstdc++

and

libc++

.

binary_search (1)

template<classForwardIt,classT=typenamestd::iterator_traits<ForwardIt>::value_type>boolbinary_search(ForwardItfirst,ForwardItlast,constT&value){returnstd::binary_search(first,last,value,std::less{});}

binary_search (2)

template<classForwardIt,classT=typenamestd::iterator_traits<ForwardIt>::value_type,classCompare>boolbinary_search(ForwardItfirst,ForwardItlast,constT&value,Comparecomp){first=std::lower_bound(first,last,value,comp);return(!(first==last)and!(comp(value,*first)));}Example

Run this code

#include<algorithm>#include<cassert>#include<complex>#include<iostream>#include<vector>intmain(){constautohaystack={1,3,4,5,9};for(constautoneedle:{1,2,3}){std::cout<<"Searching for "<<needle<<'\n';if(std::binary_search(haystack.begin(),haystack.end(),needle))std::cout<<"Found "<<needle<<'\n';elsestd::cout<<"Not found!\n";}usingCD=std::complex<double>;std::vector<CD>nums{{1,1},{2,3},{4,2},{4,3}};autocmpz=[](CDx,CDy){returnabs(x)<abs(y);};#ifdef __cpp_lib_algorithm_default_value_typeassert(std::binary_search(nums.cbegin(),nums.cend(),{4,2},cmpz));#elseassert(std::binary_search(nums.cbegin(),nums.cend(),CD{4,2},cmpz));#endif}Output:

Searching for 1 Found 1 Searching for 2 Not found! Searching for 3 Found 3 Defect reports

The following behavior-changing 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 satisfy

Compare

and T was required
to be

LessThanComparable

(strict weak ordering required) only a partitioning is required;
heterogeneous comparisons permitted

LWG 787

C++98 at most log2(N)+2 comparisons were allowed corrected to 2log2(N)+𝓞(1)See also

ranges::binary_search

(C++20)

determines if an element exists in a range using binary search
(algorithm function object)

[edit]

equal_range

finds the range of elements matching the given value using binary search
(function template & algorithm function object)

[edit]

ranges::equal_range

(C++20)

lower_bound

finds the first element not less than the given value using binary search
(function template & algorithm function object)

[edit]

ranges::lower_bound

(C++20)

upper_bound

finds the first element greater than the given value using binary search
(function template & algorithm function object)

[edit]

ranges::upper_bound

(C++20)