C++ Algorithm 库 - binary_search() 函数
描述
C++ 函数 std::algorithm::binary_search() 测试值是否以排序顺序存在。 它使用 comp 函数进行比较。
声明
以下是 std::algorithm::binary_search() 函数形式 std::algorithm 头的声明。
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 − 接受两个参数并返回一个布尔值的二进制函数。
返回值
如果 value 存在则返回 true,否则返回 false。
异常
如果元素比较或迭代器上的操作引发异常,则引发异常。
请注意,无效参数会导致未定义的行为。
时间复杂度
Logarithmic in the distance between first and 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.

