std::binary_search/std::lower_bound的底层实现
时间: 2023-11-11 21:08:07 浏览: 100
`std::binary_search`和`std::lower_bound`都是标准库中用于二分查找的算法。
`std::binary_search`用于判断一个元素是否在一个已排序的序列中存在,其底层实现通常是使用二分查找(也称折半查找)算法,即每次将查找范围折半,直到找到目标元素或者查找范围为空。
`std::lower_bound`用于查找一个已排序的序列中第一个不小于给定值的元素的位置,其底层实现也是使用二分查找算法,不同的是每次折半时,如果中间元素小于目标值,则将查找范围缩小到中间元素的右侧,否则缩小到中间元素的左侧。
具体实现可以参考以下代码:
```c++
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>
ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value)
{
while (first != last) {
ForwardIt mid = std::next(first, std::distance(first, last) / 2);
if (value > *mid) {
first = std::next(mid);
} else {
last = mid;
}
}
return first;
}
```
其中`std::next`是C++ STL中的函数,用于得到指定迭代器的后继迭代器,`std::distance`是用于计算两个迭代器之间的距离。这个代码是标准库中的实现,实际上底层实现可能会有所不同,但是都是基于二分查找算法的思想。
阅读全文
相关推荐


















