Namespaces
Variants

std::ranges:: binary_search

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
헤더에 정의됨 <algorithm>
호출 시그니처
(1)
template < std:: forward_iterator I, std:: sentinel_for < I > S,

class T, class Proj = std:: identity ,
std:: indirect_strict_weak_order
< const T * , std :: projected < I, Proj >> Comp = ranges:: less >
constexpr bool binary_search ( I first, S last, const T & value,

Comp comp = { } , Proj proj = { } ) ;
(C++20부터)
(C++26 이전까지)
template < std:: forward_iterator I, std:: sentinel_for < I > S,

class Proj = std:: identity ,
class T = std :: projected_value_t < I, Proj > ,
std:: indirect_strict_weak_order
< const T * , std :: projected < I, Proj >> Comp = ranges:: less >
constexpr bool binary_search ( I first, S last, const T & value,

Comp comp = { } , Proj proj = { } ) ;
(C++26부터)
(2)
template < ranges:: forward_range R,

class T, class Proj = std:: identity ,
std:: indirect_strict_weak_order
< const T * , std :: projected < ranges:: iterator_t < R > ,
Proj >> Comp = ranges:: less >
constexpr bool binary_search ( R && r, const T & value,

Comp comp = { } , Proj proj = { } ) ;
(C++20부터)
(C++26까지)
template < ranges:: forward_range R,

class Proj = std:: identity ,
class T = std :: projected_value_t < ranges:: iterator_t < R > , Proj > ,
std:: indirect_strict_weak_order
< const T * , std :: projected < ranges:: iterator_t < R > ,
Proj >> Comp = ranges:: less >
constexpr bool binary_search ( R && r, const T & value,

Comp comp = { } , Proj proj = { } ) ;
(C++26부터)
1) value 에 해당하는 투영된 요소가 범위 [ first , last ) 내에 나타나는지 확인합니다.
2) (1) 과 동일하지만, r 을 소스 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

ranges::binary_search 가 성공하려면 범위 [ first , last ) value 에 대해 최소한 부분적으로 정렬되어 있어야 합니다. 즉, 다음의 모든 요구사항을 충족해야 합니다:

완전히 정렬된 범위는 다음 기준을 충족합니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

목차

매개변수

first, last - 검사할 요소들의 범위 를 정의하는 반복자-감시자 쌍
r - 검사할 요소들의 범위
value - 요소들과 비교할 값
comp - 투영된 요소들에 적용할 비교 함수
proj - 요소들에 적용할 투영

반환값

true 값과 동일한 요소가 발견되면, value 그렇지 않으면 false 를 반환합니다.

복잡도

비교 및 투영 연산 횟수는 first last 사이의 거리에 대해 로그적입니다 (최대 log 2 (last - first) + O(1) 회의 비교 및 투영 연산). 그러나 std::random_access_iterator 를 모델링하지 않는 반복자-센티넬 쌍의 경우, 반복자 증감 연산 횟수는 선형입니다.

참고 사항

std::ranges::binary_search 는 투영(projection)이 value 와 동일한 요소를 찾았을 때 발견된 요소에 대한 반복자를 반환하지 않습니다. 반복자가 필요한 경우에는 대신 std::ranges::lower_bound 를 사용해야 합니다.

기능 테스트 매크로 표준 기능
__cpp_lib_algorithm_default_value_type 202403 (C++26) 목록 초기화 for algorithms ( 1,2 )

가능한 구현

struct binary_search_fn
{
    template<std::forward_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity, class T = std::projected_value_t<I, Proj>,
             std::indirect_strict_weak_order
                 <const T*, std::projected<I, Proj>> Comp = ranges::less>
    constexpr bool operator()(I first, S last, const T& value,
                              Comp comp = {}, Proj proj = {}) const
    {
        auto x = ranges::lower_bound(first, last, value, comp, proj);
        return (!(x == last) && !(std::invoke(comp, value, std::invoke(proj, *x))));
    }
    template<ranges::forward_range R, class Proj = std::identity,
             class T = std::projected_value_t<ranges::iterator_t<R>, Proj>,
             std::indirect_strict_weak_order
                 <const T*, std::projected<ranges::iterator_t<R>,
                                           Proj>> Comp = ranges::less>
    constexpr bool operator()(R&& r, const T& value, Comp comp = {}, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), value,
                       std::move(comp), std::move(proj));
    }
};
inline constexpr binary_search_fn binary_search;

예제

#include <algorithm>
#include <cassert>
#include <complex>
#include <iostream>
#include <ranges>
#include <vector>
int main()
{
    constexpr static auto haystack = {1, 3, 4, 5, 9};
    static_assert(std::ranges::is_sorted(haystack));
    for (const int needle : std::views::iota(1)
                          | std::views::take(3))
    {
        std::cout << "Searching for " << needle << ": ";
        std::ranges::binary_search(haystack, needle)
            ? std::cout << "found " << needle << '\n'
            : 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::ranges::binary_search(nums, {4, 2}, cmpz));
    #else
        assert(std::ranges::binary_search(nums, CD{4, 2}, cmpz));
    #endif
}

출력:

Searching for 1: found 1
Searching for 2: no dice!
Searching for 3: found 3

참고 항목

특정 키와 일치하는 요소들의 범위를 반환합니다
(알고리즘 함수 객체)
주어진 값보다 작지 않은 첫 번째 요소에 대한 반복자를 반환합니다
(알고리즘 함수 객체)
특정 값보다 첫 번째 요소에 대한 반복자를 반환합니다
(알고리즘 함수 객체)
범위가 주어진 요소나 부분 범위를 포함하는지 확인합니다
(알고리즘 함수 객체)
부분적으로 정렬된 범위에 요소가 존재하는지 확인합니다
(함수 템플릿)