C++ 算法库 - binary_search() 函数



描述

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

声明

以下是来自 std::algorithm 头文件的 std::algorithm::binary_search() 函数的声明。

C++98

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

参数

  • first - 指向被搜索序列初始位置的正向迭代器。

  • last - 指向被搜索序列结束位置的正向迭代器。

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

返回值

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

异常

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

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

时间复杂度

firstlast.

之间距离的对数。

示例

#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.
algorithm.htm
广告