二分查找--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

相关推荐
郝学胜-神的一滴15 分钟前
Qt 高级编程 040:按钮悬浮弹出滑块弹窗的完整攻略
开发语言·c++·qt·软件工程·用户界面
Tongzhi202631 分钟前
从部署到运维:通芝科技无感考勤一体机的全流程效率解析
运维·数据结构·科技·算法·贪心算法
Wang's Blog1 小时前
AI Agent白手起家30: 动态示例选择器之根据长度选择 Few Shot 示例
算法
oyguyteggytrrwwwrt2 小时前
自制交叉线路识别算法
算法
手写码匠2 小时前
华为云Flexus+DeepSeek征文|Dify 多智能体协同编排实战:R1 规划 + V3 执行,构建企业 Agent 团队
人工智能·深度学习·算法·aigc
晓天衡宇•评测社区3 小时前
FSR-Bench 前沿科学推理榜单发布:GPT-5.5 居首,“会推理”未必“能答对”
算法
程序喵大人5 小时前
【C++进阶】STL算法与函数对象 - 02 sort为什么需要随机访问迭代器
开发语言·c++·算法
hanlin035 小时前
动态规划专练:力扣第121、122题
笔记·算法·leetcode
To_OC5 小时前
LC 74 搜索二维矩阵:换皮的二分查找,我居然一开始没看出来
javascript·算法·leetcode
文心快码BaiduComate5 小时前
文心快码荣获“中国优秀软件产品”,实力再获国家级认可
算法·代码规范