二分搜索:lower_bound 与 upper_bound 函数

基本用法:

lower_bound 和upper_bound需要用在一个有序数组和容器中。
(1)lower_bound (first,last,val)用来寻找在数组和容器[first,last)的范围内,第一个值大于等于val的元素的位置。如果是数组,则返回该位置的指针,如果是容器,则返回该位置的迭代器。
(2)upper_bound(first,last,val)用来寻找在数组和容器[first,last)的范围内,第一个值大于val的元素的位置。如果是数组,则返回该位置的指针,如果是容器,则返回该位置的迭代器。

显然,如果数组和容器中没有需要寻找的元素。lower_bound 和upper_bound均返回可以插入该元素的位置的指针和迭代器(即假设存在该元素时,该元素应当在的位置)。

头文件:algorithm

复杂度:lower_bound 和upper_bound均为O(\log (last-frist))

示例如下:

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
	int a[10]={1,2,2,3,3,3,5,5,5,5};
	int *lowerpos=lower_bound(a,a+10,-1);
	int *upperpos=upper_bound(a,a+10,-1);
	cout<<lowerpos-a<<","<<upperpos-a<<endl;
	//寻找1
	lowerpos=lower_bound(a,a+10,1);
	upperpos=upper_bound(a,a+10,1);
	cout<<lowerpos-a<<","<<upperpos-a<<endl;
	//寻找3
	lowerpos=lower_bound(a,a+10,3);
	upperpos=upper_bound(a,a+10,3);
	cout<<lowerpos-a<<","<<upperpos-a<<endl;
	//寻找4
	lowerpos=lower_bound(a,a+10,4);
	upperpos=upper_bound(a,a+10,4);
	cout<<lowerpos-a<<","<<upperpos-a<<endl;
	//寻找6
	lowerpos=lower_bound(a,a+10,6);
	upperpos=upper_bound(a,a+10,6);
	cout<<lowerpos-a<<","<<upperpos-a<<endl;
	return 0;
} 

输出结果:

0,0
0,1
3,6
6,6
10,10

如果只是想获得欲查元素的下标

显然,就可以不使用临时指针,而直接令返回值减去数组首地址即可

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
	int a[10]={1,2,2,3,3,3,5,5,5,5};
	//寻找3
	cout<<lower_bound(a,a+10,3)-a<<","<<upper_bound(a,a+10,3)-a<<endl;
	return 0;
} 

输出结果:

3,6

猜你喜欢

转载自blog.csdn.net/weixin_45884316/article/details/105793575