C++ 演算法 binary_search() 函式
示例
查詢值是否存在於已排序的向量中
vector<int> numbers = {1, 7, 3, 5, 9, 2};
sort(numbers.begin(), numbers.end());
if (binary_search(numbers.begin(), numbers.end(), 5)) {
cout << "The number 5 was found!";
} else {
cout << "The number 5 was not found.";
}
自己動手試一試 »
定義和用法
binary_search()
函式是一種高效的演算法,用於檢查一個值是否存在於某個資料範圍內。
資料範圍必須已經排序。如果資料範圍未排序,則該函式可能會返回不正確的結果。可以使用 sort() 函式對資料範圍內的元素進行排序。
資料範圍由迭代器指定。
語法
binary_search(iterator start, iterator end, <type> value);
<type>
指的是範圍包含的資料型別。
引數值
引數 | 描述 |
---|---|
start | 必需。指向正在搜尋的資料範圍起點的迭代器。 |
end | 必需。指向正在搜尋的資料範圍終點的迭代器。將搜尋該位置之前的元素,但該位置的元素不被包含在內。 |
value | 必需。要搜尋的值。 |
技術詳情
返回 | 布林值
|
---|
相關頁面
在我們 資料結構教程 中瞭解更多關於資料結構的資訊。
在我們 迭代器教程 中瞭解更多關於迭代器的資訊。
在我們 演算法教程 中瞭解更多關於演算法的資訊。