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

相关推荐
CHEEVEN_QY1 分钟前
液冷板热阻计算与流阻优化的实战方法
人工智能·算法·机器学习
CQU_JIAKE8 分钟前
10.2【A】
数据结构
无名猿16 分钟前
对象构造与析构顺序全解:声明顺序、继承链与逆序析构
c++·内存管理·调试技巧·现代c++
殷色玫瑰30 分钟前
C/C++ 内存管理详解:从内存分布到 new/delete 底层原理
java·linux·c语言·c++
C++ 老炮儿的技术栈42 分钟前
不一样的数值交换
数据结构·c++·人工智能·算法·c·csdn开发云
C++ 老炮儿的技术栈1 小时前
main函数之后的调用
c语言·c++·人工智能·qt·mfc·c
知识分享小能手1 小时前
C++ 学习教程,从入门到精通,C++ 友元、异常和其他特性 — 详细知识点(15)
开发语言·c++·学习
hahaha60162 小时前
Shades-of-Gray (SoG) 算法--白平衡算法
人工智能·嵌入式硬件·算法·计算机视觉
ebiobiz2 小时前
极海 APM32 使用 Nimmake 编译指南
c++·python·单片机·嵌入式硬件·mcu
青山木2 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划