Namespaces
Variants

std::ranges::binary_search

ja.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 が true となる射影された要素はすべて、式 false が 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 である。

完全にソートされた範囲はこれらの条件を満たします。

このページで説明されている関数のようなエンティティは アルゴリズム関数オブジェクト(非公式に niebloid と呼ばれます)です。つまり:

パラメータ

first, last - 検査する要素の 範囲 を定義するイテレータ-センチネルペア
r - 検査する要素の範囲
value - 要素と比較する値
comp - 投影された要素に適用する比較関数
proj - 要素に適用する投影

戻り値

true valueに等しい要素が見つかった場合、 value それ以外の場合 false を返す。

計算量

比較と射影の実行回数は、 first と last 間の距離に対して対数的です(最大で log 2 (last - first) + O(1) 回の比較と射影)。ただし、 std::random_access_iterator をモデル化しないイテレータ-番兵ペアの場合、イテレータのインクリメント回数は線形になります。

注記

std::ranges::binary_search は、射影が value と等しい要素が見つかった場合でも、見つかった要素へのイテレータを返しません。イテレータが必要な場合は、 std::ranges::lower_bound を代わりに使用すべきです。

機能テスト マクロ 値 標準 機能
__cpp_lib_algorithm_default_value_type 202403 (C++26) リスト初期化 アルゴリズム用 ( 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;
**注記**: 提供されたC++コードはHTMLタグ内の`
`ブロックに含まれており、翻訳対象外のテキストとして指定されています。また、HTMLタグや属性、C++固有の用語も翻訳しないように指示されています。そのため、元のコードは完全に保持され、翻訳は行われていません。

例

#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

関連項目

二分探索を用いて、指定された値と一致する要素の範囲を探す
(アルゴリズム関数オブジェクト)
二分探索を用いて、指定された値より小さくない最初の要素を探す
(アルゴリズム関数オブジェクト)
二分探索を用いて、指定された値より大きい最初の要素を探す
(アルゴリズム関数オブジェクト)
範囲に指定された要素または部分範囲が含まれているかを調べる
(アルゴリズム関数オブジェクト)
二分探索を用いて、範囲内に要素が存在するかを判定する
(関数テンプレート)