std::binary_search
在标头 <algorithm> 定义
|
||
template< class ForwardIt, class T > bool binary_search( ForwardIt first, ForwardIt last, const T& value ); |
(1) | (C++20 起 constexpr) |
template< class ForwardIt, class T, class Compare > bool binary_search( ForwardIt first, ForwardIt last, |
(2) | (C++20 起 constexpr) |
检查在已划分范围 [
first,
last)
中是否出现与 value 等价的元素。
如果 如果满足以下任意条件,那么行为未定义:
|
(C++20 前) |
等价于 std::binary_search(first, last, value, std::less{})。 |
(C++20 起) |
[
first,
last)
中存在迭代器 iter 使得 bool(comp(*iter, value)) && !bool(comp(value, *iter)) 是 true,那么返回 true。否则返回 false。-
[
first,
last)
的某些元素 elem 使得无法通过 bool(comp(elem, value)) 得出 !bool(comp(value, elem))。 -
[
first,
last)
的元素 elem 没有按表达式 bool(comp(elem, value)) 和 !bool(comp(value, elem)) 划分。
目录 |
[编辑] 参数
first, last | - | 要检验的已划分元素范围 |
value | - | 要与元素比较的值 |
comp | - | 如果第一个实参先序于第二个则返回 true 的二元谓词。 谓词函数的签名应等价于如下: bool pred(const Type1 &a, const Type2 &b); 虽然签名不必有 const & ,函数也不能修改传递给它的对象,而且必须接受(可为 const 的)类型 |
类型要求 | ||
-ForwardIt 必须满足老式向前迭代器 (LegacyForwardIterator) 。
| ||
-Compare 必须满足二元谓词 (BinaryPredicate) 。不要求满足 比较 (Compare) 。
|
[编辑] 返回值
找到等价于 value 的元素时返回 true,否则返回 false。
[编辑] 复杂度
给定 N 为 std::distance(first, last):
2(N)+O(1) 次比较函数 comp。
然而,如果 ForwardIt
不是老式随机访问迭代器 (LegacyRandomAccessIterator) ,那么迭代器自增次数与 N 成线性。
[编辑] 注解
尽管 std::binary_search
只要求 [
first,
last)
已划分,但是该算法通常会在 [
first,
last)
已排序的情况下使用,此时二分查找对于任意 value 都有效。
std::binary_search
只会检查是否存在等价元素。需要获取到该元素(如果存在)的迭代器时应改用 std::lower_bound。
[编辑] 可能的实现
binary_search (1) |
---|
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) and !(value < *first)); } |
binary_search (2) |
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, comp); return (!(first == last) and !(comp(value, *first))); } |
[编辑] 示例
#include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> haystack{1, 3, 4, 5, 9}; std::vector<int> needles{1, 2, 3}; for (const auto needle : needles) { std::cout << "正在搜索 " << needle << '\n'; if (std::binary_search(haystack.begin(), haystack.end(), needle)) std::cout << "找到了 " << needle << '\n'; else std::cout << "没找到!\n"; } }
输出:
正在搜索 1 找到了 1 正在搜索 2 没找到! 正在搜索 3 找到了 3
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 270 | C++98 | Compare 需要满足比较 (Compare) ,并且 T 需要是可小于比较 (LessThanComparable) 的(要求严格弱序) |
只需要划分;容许异相比较 |
LWG 787 | C++98 | 最多允许 log 2(N)+2 次比较 |
改成 log 2(N)+O(1) 次 |
[编辑] 参阅
返回匹配特定键值的元素范围 (函数模板) | |
返回指向第一个不小于 给定值的元素的迭代器 (函数模板) | |
返回指向第一个大于 给定值的元素的迭代器 (函数模板) | |
(C++20) |
确定元素是否存在于某范围中 (niebloid) |