二分查找--C++实现

1. 简介

满足有序性,每次排除一半的可能性。

2. 实现

2.1 手写
cpp 复制代码
int bin_search(vector<int> &arr,int v) {
	int hi = arr.size() - 1;
	int lo = 0;
	
	while ( lo <= hi)
	{
		int mid = (lo + hi) >> 1;
		if (arr[mid] < v)
			lo = mid + 1;
		else
			hi = mid - 1;
	}
	return hi;
}
2.2 STL
  1. lower_bound()
    C++20之后才有
    找到第一不小于某个值的位置
  • 使用
cpp 复制代码
lower_bound(potions.begin(), potions.end(), tar);
  • 实现
cpp 复制代码
template<class ForwardIt, class T>
ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value)
{
    ForwardIt it;
    typename std::iterator_traits<ForwardIt>::difference_type count, step;
    count = std::distance(first, last);
 
    while (count > 0)
    {
        it = first; 
        step = count / 2; 
        std::advance(it, step);
 
        if (*it < value)
        {
            first = ++it; 
            count -= step + 1; 
        }
        else
            count = step;
    }
 
    return first;
}
  1. upper_bound()
    找到第一个严格大于某个值的位置
    C++20之后才能用。
  • 使用
cpp 复制代码
upper_bound(potions.begin(), potions.end(), tar);
  • 实现
cpp 复制代码
template<class ForwardIt, class T>
ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value)
{
    ForwardIt it;
    typename std::iterator_traits<ForwardIt>::difference_type count, step;
    count = std::distance(first, last);
 
    while (count > 0)
    {
        it = first; 
        step = count / 2; 
        std::advance(it, step);
 
        if (!(value < *it))
        {
            first = ++it;
            count -= step + 1;
        } 
        else
            count = step;
    }
 
    return first;
}

3. Ref

cppreference

相关推荐
晓纪同学7 分钟前
EffctiveC++_第三章_资源管理
开发语言·c++·算法
沐雪轻挽萤23 分钟前
6. C++17新特性-编译期 if 语句 (if constexpr)
开发语言·c++
水云桐程序员25 分钟前
C语言编程基础,输入与输出
c语言·开发语言·算法
ZPC821027 分钟前
MoveIt Servo 与自己编写的 Action Server 通信
人工智能·算法·机器人
jllllyuz29 分钟前
采用核函数的极限学习机(KELM)MATLAB实现
算法
apcipot_rain38 分钟前
【天梯赛】2026天梯赛模拟赛——题解
开发语言·c++·算法·蓝桥杯·天梯赛
-To be number.wan40 分钟前
重新认识一下“私有继承”
c++·学习
江奖蒋犟1 小时前
【C++】红黑树
开发语言·c++
lclin_20201 小时前
【大恒相机】C++ 设备枚举+打开关闭+启停采集(基础入门)
c++·工业相机·大恒相机·galaxysdk
.柒宇.1 小时前
力扣hot100之最大子数组和(Java版)
数据结构·算法·leetcode