lower_bound/upper_bound的重载

lower_bound/upper_bound的重载

升序容器,正常使用

在一个升序的容器当中,lower_bound是寻找第一个大于等于target的目标;
upper_bound是寻找第一个大于target的目标,那么,他们的实现大致就是这样子的:

lower_bound大致实现

int func(int left, int right, int target) {
	int l = left, r = right;
	while(l < r) {
		int mid = l + r >> 1;
		if (container[mid] >= target)
			r = mid;
		else
			l = mid + 1;
	}
}

upper_bound大致实现

int func(int left, int right, int target) {
	int l = left, r = right;
	while(l < r) {
		int mid = l + r >> 1;
		if (container[mid] <= target)
			l = mid + 1;
		else
			r = mid;
	}
}

平时使用的时候,我们也可以通过lower_bound - 1来寻找最后一个小于target的元素。

降序容器,重载使用

如果给定的容器是降序的,那上面那套逻辑就没法用了(二分的指针移动是按照升序的情况来写的)

这时候想让函数正常工作,就需要把不等号的方向翻转一下,实际的操作就是greater<int>()重载一下,

这样子,lower_bound就变成了:
找到序列中最左边的小于等于target的数字;
upper_bound就变成了:
找到序列中最左边小于target的数字。

posted @ 2025-03-04 21:36  Gold_stein  阅读(71)  评论(0)    收藏  举报