目录

algorithm::binary_search()

描述 (Description)

C ++函数std::algorithm::binary_search()测试值是否存在于排序序列中。 它使用运算符“进行比较。

声明 (Declaration)

以下是std :: algorithm :: binary_search()函数形式std :: algorithm头的声明。

C++98

template <class ForwardIterator, class T>
bool binary_search(ForwardIterator first, ForwardIterator last, const T& val);

参数 (Parameters)

  • first - 将迭代器转发到搜索序列的初始位置。

  • last - 将迭代器转发到搜索序列的最终位置。

  • val - 要在范围内搜索的值。

返回值

如果值存在则返回true,否则返回false。

异常 (Exceptions)

如果元素比较或迭代器上的操作抛出异常,则抛出异常。

请注意,无效参数会导致未定义的行为。

时间复杂

对数在第一个最后一个之间的距离。

例子 (Example)

以下示例显示了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.
↑回到顶部↑
WIKI教程 @2018