Namespaces
Variants

std::ranges::binary_search

출처 ko.cppreference.net
 
 
알고리즘 라이브러리
제약된 알고리즘 및 범위에 대한 알고리즘 (C++20)
제약된 알고리즘, 예: ranges::copy, ranges::sort, ...
정렬 및 관련 연산
분할 연산
(C++11)    

정렬 연산
이진 탐색 연산
(분할된 범위에 대해)
집합 연산 (정렬된 범위에 대해)
병합 연산 (정렬된 범위에 대해)
힙 연산
최소/최대 연산
(C++11)
(C++17)
사전식 비교 연산
순열 연산


 
제약된 알고리즘
이 메뉴의 모든 이름은 네임스페이스std::ranges
비수정 시퀀스 연산
수정 시퀀스 연산
분할 연산
정렬 연산
이진 탐색 연산 (정렬된 범위에 대해)
       
       
집합 연산 (정렬된 범위에 대해)
힙 연산
최소/최대 연산
       
       
순열 연산
폴드 연산
수치 연산
(C++23)            
초기화되지 않은 저장소에 대한 연산
반환 타입
 
헤더에 정의됨 <algorithm>
호출 시그니처
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 = {} );
(1) (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부터)
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 = {} );
(2) (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에 대해 적어도 부분적으로 정렬되어 있어야 합니다. 즉, 다음 요구 사항을 모두 만족해야 합니다:

  • std::invoke(comp, std::invoke(proj, element), value)에 대해 분할됨 (즉, 표현식이 true인 모든 프로젝션 요소는 표현식이 false인 모든 요소보다 앞에 옵니다).
  • !std::invoke(comp, value, std::invoke(proj, element))에 대해 분할됨.
  • 모든 요소에 대해, std::invoke(comp, std::invoke(proj, element), value)이 true이면 !std::invoke(comp, value, std::invoke(proj, element))도 true입니다.

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

이 페이지에서 설명하는 함수형 엔터티는 알고리즘 함수 객체 (비공식적으로 니블로이드로 알려짐)입니다. 즉:

매개변수

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

참조

이진 탐색을 사용하여 주어진 값과 일치하는 요소들의 범위를 찾습니다
(알고리즘 함수 객체)
이진 탐색을 사용하여 주어진 값보다 작지 않은 첫 번째 요소를 찾습니다
(알고리즘 함수 객체)
이진 탐색을 사용하여 주어진 값보다 큰 첫 번째 요소를 찾습니다
(알고리즘 함수 객체)
범위에 주어진 요소 또는 부분 범위가 포함되어 있는지 확인합니다
(알고리즘 함수 객체)
이진 탐색을 사용하여 범위에 요소가 존재하는지 확인합니다
(함수 템플릿)