STL lower_bound, upper_bound

总结:

1、用之前先用sort排好序

2、想要得到找到数字在数组中的下标,通过返回的地址减去起始地址begin,int t1 = lower_bound(board,board+5,3)-board;

3、lower_bound:是第一个大于等于;upper_bound:是第一个大于,不包含int x.

lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序的数组(先sort排序)中进行查找的。

头文件:#include <algorithm>

时间复杂度:一次查询O(log n),n为数组长度。

lower_bound:

功能:从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。 查找非递减序列[first,last) 第一个大于或等于某个元素的位置。

返回值:如果找到返回找到元素的地址否则返回last的地址。(这样不注意的话会越界,小心)

用法:通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。int t=lower_bound(a+l,a+r,key)-a;(a是数组)。

upper_bound:

功能:查找非递减序列[first,last) 内第一个大于某个元素的位置。

返回值:如果找到返回找到元素的地址否则返回last的地址。(同样这样不注意的话会越界,小心)

用法:int t=upper_bound(a+l,a+r,key)-a;(a是数组)。


代码:

#include <iostream>
#include <algorithm>
 
using namespace std;
 
int board[5] = {1,2,3,4,5};
 
int main(){
	
	sort(board,board+5);//先sort排序,从小到大
    //第一个大于等于,start到end-1内查找,所以第二个参数是数量而非索引
	int t1 = lower_bound(board,board+5,3)-board;//第一个大于等于的地址
	int t2 = upper_bound(board,board+5,3)-board;//第一个大于
	cout<<t1<<' '<<t2<<endl;
	
	return 0;
} 


重点参考:https://blog.csdn.net/vocaloid01/article/details/80583539

发布了176 篇原创文章 · 获赞 84 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/try_again_later/article/details/96461579