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