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
廣告