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

头文件:#include <algorithm>

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

图示:C++ STL lower_bound,upper_bound的使用总结

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;
} 

结果:

C++ STL 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){//比较函数 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;
} 

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

可见结果没变由此可以得出一个结论,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;
} 

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

原文链接: https://www.cnblogs.com/vocaloid01/p/9514099.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/275341

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午12:58
下一篇 2023年2月15日 上午12:58

相关推荐