C++ STL lower_bound,upper_bound的使用总结

头文件:#include <algorithm>

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

图示:

lower_bound:

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

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

用法: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);
	int t1 = lower_bound(board,board+5,3)-board;
	int t2 = upper_bound(board,board+5,3)-board;
	cout<<t1<<' '<<t2<<endl;
	
	return 0;
} 

结果:

加了比较函数后:

#include <iostream>
#include <algorithm>

using namespace std;

int board[5] = {1,2,3,4,5};

bool cmp(int a,int b){//比较函数 1
	return a < b;
}

int main(){
	
	sort(board,board+5);
	int t1 = lower_bound(board,board+5,3,cmp)-board;
	int t2 = upper_bound(board,board+5,3,cmp)-board;
	cout<<t1<<' '<<t2<<endl;
	
	return 0;
} 

可见结果没变由此可以得出一个结论,cmp里函数应该写的是小于运算的比较。

如果加上了等号,lower_bound和upper_bound两个函数功能就刚好反过来了:

#include <iostream>
#include <algorithm>

using namespace std;

int board[5] = {1,2,3,4,5};

bool cmp(int a,int b){//比较函数 2
	return a <= b;
}

int main(){
	
	sort(board,board+5);
	int t1 = lower_bound(board,board+5,3,cmp)-board;
	int t2 = upper_bound(board,board+5,3,cmp)-board;
	cout<<t1<<' '<<t2<<endl;
	
	return 0;
} 



转载于:https://www.cnblogs.com/vocaloid01/p/9514099.html

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值