Cpp-standard-library-cpp-algorithm-binary-search-custom
提供:Dev Guides
C ++アルゴリズムライブラリ-binary_search()関数
説明
- C ++関数* std
- algorithm :: binary_search()*は、ソートされたシーケンスに値が存在するかどうかをテストします。 比較のために `+ comp +`関数を使用します。
宣言
- 以下は、std
- algorithmヘッダーからのstd :: algorithm :: binary_search()関数の宣言です。
C 98
template <class ForwardIterator, class T, class Compare>
bool binary_search (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);
パラメーター
- first -イテレータを検索されたシーケンスの初期位置に転送します。
- last -検索されたシーケンスの最終位置に反復子を転送します。
- val -範囲内で検索する値。
- comp -2つの引数を受け取り、boolを返すバイナリ関数。
戻り値
値が存在する場合はtrue、そうでない場合はfalseを返します。
例外
要素比較またはイテレータの操作が例外をスローした場合、例外をスローします。
無効なパラメータは未定義の動作を引き起こすことに注意してください。
時間の複雑さ
`+ first `と ` last +`の間の距離の対数。
例
- 次の例は、std
- algorithm :: binary_search()関数の使用法を示しています。
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
bool comp(string s1, string s2) {
return (s1 == s2);
}
int main(void) {
vector<string> v = {"ONE", "Two", "Three"};
bool result;
result = binary_search(v.begin(), v.end(), "one", comp);
if (result == true)
cout << "String \"one\" exist in vector." << endl;
v[0] = "Ten";
return 0;
}
上記のプログラムをコンパイルして実行すると、次の結果が生成されます-
String "one" exist in vector.