C++ 演算法庫 - binary_search() 函式



描述

C++ 函式 **std::algorithm::binary_search()** 用於測試某個值是否存在於已排序的序列中。comp函式用於比較。

宣告

以下是來自 std::algorithm 標頭檔案的 std::algorithm::binary_search() 函式的宣告。

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** - 接受兩個引數並返回 bool 值的二元函式。

返回值

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

異常

如果元素比較或迭代器操作引發異常,則丟擲異常。

請注意,無效引數會導致未定義的行為。

時間複雜度

firstlast.

示例

以下示例演示了 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.
algorithm.htm
廣告