目录

algorithm::binary_search()

描述 (Description)

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

声明 (Declaration)

以下是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);

参数 (Parameters)

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

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

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

  • comp - 接受两个参数并返回bool的二进制函数。

返回值

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

异常 (Exceptions)

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

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

时间复杂

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

例子 (Example)

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