std::binary_search
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <algorithm> 中定义
|
||
template< class ForwardIt, class T > bool binary_search( ForwardIt first, ForwardIt last, const T& value ); |
(1) | |
template< class ForwardIt, class T, class Compare > bool binary_search( ForwardIt first, ForwardIt last, const T& value, Compare comp ); |
(2) | |
检查是否已排序的范围
[first, last)
包含一个元素等于value
。 operator<的第一个版本使用比较的元素,第二个版本使用给定的比较函数comp
.原文:
Checks if the sorted range
[first, last)
contains an element equal to value
. The first version uses operator< to compare the elements, the second version uses the given comparison function comp
.目录 |
[编辑] 参数
first, last | - | 检查的元素
|
value | - | 值进行比较的元素
|
comp | - | comparison function which returns true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b); The signature does not need to have const &, but the function must not modify the objects passed to it. |
类型要求 | ||
-ForwardIt 必须满足 ForwardIterator 的要求。
|
[编辑] 返回值
true发现,如果一个元素等于
value
false否则.原文:
true if an element equal to
value
is found, false otherwise.[编辑] 复杂度
first
和last
之间的距离在对数原文:
Logarithmic in the distance between
first
and last
[编辑] 可能的实现
版本一 |
---|
template<class ForwardIt, class T> bool binary_search(ForwardIt first, ForwardIt last, const T& value) { first = std::lower_bound(first, last, value); return (first != last && !(value < *first)); } |
版本二 |
template<class ForwardIt, class T, class Compare> bool binary_search(ForwardIt first, ForwardIt last, const T& value, Compare comp) { first = std::lower_bound(first, last, value); return (first != last && !(comp(value, *first)); } |
[编辑] 示例
#include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> haystack {1, 3, 4, 5, 9}; std::vector<int> needles {1, 2, 3}; for (auto needle : needles) { std::cout << "Searching for " << needle << '\n'; if (std::binary_search(haystack.begin(), haystack.end(), needle)) { std::cout << "Found " << needle << '\n'; } else { std::cout << "no dice!\n"; } } }
输出:
Searching for 1 Found 1 Searching for 2 no dice! Searching for 3 Found 3
[编辑] 另请参阅
返回匹配特定键值的元素区间 (函数模板) |