std::binary_search(3)
πΈ std::binary_search β C++ Standard Library πΈ
okay so bestie, welcome to the manual page for std::binary_search(3) β C++ Standard Library edition. Itβs giving algorithm royalty, and weβre gonna read it together without losing a single detail. π
β¨
π NAME π
std::binary_search β std::binary_search.
β¨ SYNOPSIS β¨
Defined in header <algorithm> β noted, bestie β¨
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 );
(1) β 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 );
(2) β since C++26
π¦ DESCRIPTION π¦
Checks if an element equivalent to value appears within the partitioned range [first, last).
1) The equivalence is checked using operator<:
If !bool(*iter < value) && !bool(value < *iter) is true for some iterator iter in [first, last), returns true. Otherwise returns false.
If any of the following conditions is satisfied, the behavior is undefined: (until C++20)
- For any element
elemof[first, last),bool(elem < value)does not imply!bool(value < elem). - The elements
elemof[first, last)are not partitioned with respect to expressionsbool(elem < value)and!bool(value < elem).
Equivalent to std::binary_search(first, last, value, std::less{}). (since C++20)
2) The equivalence is checked using comp:
If !bool(comp(*iter, value)) && !bool(comp(value, *iter)) is true for some iterator iter in [first, last), returns true. Otherwise returns false.
If any of the following conditions is satisfied, the behavior is undefined:
- For any element
elemof[first, last),bool(comp(elem, value))does not imply!bool(comp(value, elem)). - The elements
elemof[first, last)are not partitioned with respect to expressionsbool(comp(elem, value))and!bool(comp(value, elem)).
π PARAMETERS π
first, lastβ the partitioned range of elements to examine.valueβ value to compare the elements to.compβ binary predicate which returnstrueif the first argument is ordered before the second.
The signature of the predicate function should be equivalent to the following:
bool pred(const Type1 &a, const Type2 &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 types Type1 and Type2 must be such that an object of type T can be implicitly converted to both Type1 and Type2, and an object of type ForwardIt can be dereferenced and then implicitly converted to both Type1 and Type2.
π TYPE REQUIREMENTS π
ForwardItmust meet the requirements ofLegacyForwardIterator.Comparemust meet the requirements ofBinaryPredicate. It is not required to satisfyCompare.
π RETURN VALUE π
true if an element equivalent to value is found, false otherwise.
π₯ COMPLEXITY π₯
Given N as std::distance(first, last):
- At most
logβ(N)+O(1)comparisons withvalueusingoperator<(until C++20)orstd::less{}(since C++20). - At most
logβ(N)+O(1)applications of the comparatorcomp.
However, if ForwardIt is not a LegacyRandomAccessIterator, the number of iterator increments is linear in N.
π NOTES π
- Although
std::binary_searchonly 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_searchonly checks whether an equivalent element exists. To obtain an iterator to that element (if exists),std::lower_boundshould be used instead.
Feature-test macro:
__cpp_lib_algorithm_default_value_typeβ value202403, stdC++26, feature: List-initialization for algorithms(1,2).
π§ POSSIBLE IMPLEMENTATION π§
See also the implementations in libstdc++ and libc++.
binary_search (1)
template<class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type>
bool binary_search(ForwardIt first, ForwardIt last, const T& value)
{
return std::binary_search(first, last, value, std::less{});
}
binary_search (2)
template<class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type,
class Compare>
bool binary_search(ForwardIt first, ForwardIt last, const T& value, Compare comp)
{
first = std::lower_bound(first, last, value, comp);
return (!(first == last) and !(comp(value, *first)));
}
π EXAMPLE π
Run this code β yes bestie, actually run it:
#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 << "No dice!\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
}
π OUTPUT π
Searching for 1
Found 1
Searching for 2
no dice!
Searching for 3
Found 3
π DEFECT REPORTS π
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
LWG 270, applied toC++98β Behavior as published:Comparewas required to satisfyCompareandTwas required to beLessThanComparable(strict weak ordering required). Correct behavior: only a partitioning is required; heterogeneous comparisons permitted.LWG 787, applied toC++98β Behavior as published: at mostlogβ(N)+2comparisons were allowed. Correct behavior: corrected tologβ(N)+O(1).
π SEE ALSO π
equal_rangeβ returns range of elements matching a specific key (function template).lower_boundβ returns an iterator to the first element not less than the given value (function template).upper_boundβ returns an iterator to the first element greater than a certain value (function template).ranges::binary_search(C++20)β determines if an element exists in a partially-ordered range (niebloid).
Okay bestie, thatβs the whole page β go binary-search something iconic. πβ¨
Source/vibe check: http://cppreference.com Β· version/date: 2024.06.10 Β· page: std::binary_search(3) π«Ά
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms