C++ Algorithm 库 - binary_search() 函数
描述
C++ 函数 std::algorithm::binary_search() 测试值是否以排序顺序存在。它使用 operator< 来进行比较。
声明
以下是 std::algorithm::binary_search() 函数形式 std::algorithm 头的声明。
C++98
template <class ForwardIterator, class T> bool binary_search(ForwardIterator first, ForwardIterator last, const T& val);
参数
first − 将迭代器转发到搜索序列的初始位置。
last − 将迭代器转发到搜索序列的最终位置。
val − 要在范围内搜索的值。
返回值
如果 value 存在则返回 true,否则返回 false。
异常
如果元素比较或迭代器上的操作引发异常,则引发异常。
请注意,无效参数会导致未定义的行为。
时间复杂度
Logarithmic in the distance between first and last.
示例
以下示例显示了 std::algorithm::binary_search() 函数的用法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void) {
vector<int> v = {1, 2, 3, 4, 5};
bool result;
result = binary_search(v.begin(), v.end(), 3);
if (result == true)
cout << "Element 3 exist in vector." << endl;
v[2] = 10;
result = binary_search(v.begin(), v.end(), 3);
if (result == false)
cout << "Element 3 doesn't exist in vector." << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Element 3 exist in vector. Element 3 doesn't exist in vector.

