数组中的二分查找函数:lower_bound【第一个 >= 目标值的元素的值或者下标】 和 upper_bound【第一个 > 目标值的元素的值或者下标】

前提:数组必须是有序的【最好是升序的】

举例:数组:[1, 2, 3, 3, 3, 7,8]查找目标值:3

lower_bound → 指向第一个 3的迭代器,解引用后可得到值

upper_bound → 指向第一个比 3 大的数(7),解引用后可得到值

【在数组中是否可以找到目标值】可执行代码:

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
vector<int> a(N);
int main(){
a={1,2,3,3,3,7,8};
int target=5;//将要查找的值设为3. 
vector<int>::iterator ret1=lower_bound(a.begin(),a.begin()+7,target);//返回数组中第一次出现3的位置的下标。
//如果数组中没有找到这个元素,就返回数组中第一次出现大于3的位置的下标
vector<int>::iterator ret2=upper_bound(a.begin(),a.begin()+7,target);//返回数组中第一次出现大于3的位置的下标 
cout<<*ret1<<endl<<*ret2<<endl;
if(target==*ret1) cout<<"在数组中可以找到目标值:"<<target<<endl;
else cout<<"在数组中不可以找到目标值"<<endl;
}

运行结果:

lower_bound -a.begin()→ 指向第一个 3的下标

upper_bound -a.begin()→ 指向第一个比 3 大的数(7)的下标

【得到目标值第一次出现的下标和目标值最后一次出现下标的下一个位置】可执行代码:

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
vector<int> a(N);
int main(){
a={1,2,3,3,3,7,8};
int target=3;//将要查找的值设为3. 
int ret1=lower_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现3的位置的下标。
//如果数组中没有找到这个元素,就返回数组中第一次出现大于3的位置的下标
int ret2=upper_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现大于3的位置的下标 
cout<<ret1<<endl<<ret2;
}

运行结果:

【修改一下,将目标值改为数组中未出现的元素时lower_bound()和upper_bound()函数值的变化】可执行代码:

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10;
vector<int> a(N);
int main(){
a={1,2,3,3,3,7,8};
int target=5;//将要查找的值设为5. 
int ret1=lower_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现3的位置的下标。
//如果数组中没有找到这个元素,就返回数组中第一次出现大于5的位置的下标
int ret2=upper_bound(a.begin(),a.begin()+7,target)-a.begin();//返回数组中第一次出现大于5的位置的下标 
cout<<ret1<<endl<<ret2;
}

运行结果:

相关推荐
alphaTao7 分钟前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
青岚_Nox12 分钟前
# C语言实战:函数完全指南——从基础概念到static/extern深度解析
算法
CCCCCCCCharlie23 分钟前
深入解析I/O底层:文件描述符与缓冲区真相
linux·开发语言·c++·算法
Cccp.1231 小时前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
学逆向的1 小时前
C 选择结构的执行效率分析
c语言·开发语言·算法·网络安全
wzdark1 小时前
动态规划算法的状态转移矩阵可视化分析5
算法·矩阵·动态规划
Pniubi1 小时前
力扣70爬楼梯
数据结构·算法·leetcode
人工智能培训1 小时前
具身智能环境交互与学习范式原理
大数据·linux·人工智能·学习·算法·机器学习
纪念 2292 小时前
C++算法(三)
开发语言·c++·算法
学不会pwn不改名2 小时前
时间复杂度与空间复杂度详解
算法