lower_bound()与upper_bound()


lower_bound()函数与upper_bound()函数在头文件中;
使用时添加头文件:

#include <algorithm>

解释:lower_bound()和upper_bound()为二分法查找元素,其时间复杂度为O(log n)。
使用条件:有序数组。

一,在数组中使用lower_bound()upper_bound()

1. int i_lower = lower_bound(arr, arr + n, val) - arr;
作用:lower_bound()函数返回数组 arr 中大于等于 val 的第一个元素的地址,若arr中的元素均小于 val 则返回尾后插入val位置地址。

2. int i_upper = upper_bound(arr, arr + n, 8) - arr
作用:upper_bound()函数返回数组 arr 中大于 val 的第一个元素的地址,若 arr 中的元素均小于等于 val 则返回尾后插入val位置地址。
示例:

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    const int n = 6;
	int arr[n]{ 0,1,5,8,10,11};
	int i_lower = lower_bound(arr, arr + n, 8) - arr;//大于等于8
    int i_upper = upper_bound(arr, arr + n, 8) - arr;//大于8
	cout << "i_lower:" << i_lower << endl;//i_lower:3
    cout << "i_upper:" << i_upper << endl;//i_upper:4
	int j_lower = lower_bound(arr, arr + n, 10) - arr;
    int j_upper = upper_bound(arr, arr + n, 10) - arr;
	cout << "j_lower:" << j_lower << endl;//j_lower:4
    cout << "j_upper:" << j_upper << endl;//j_upper:5
	return 0;
}

二、STL中的lower_bound()和upper_bound()

用法与数组中基本一样,但在STL中,返回值为迭代器。但在vector中,可以是迭代器也可以是位置。
(1)vector动态数组

int main()
{
	vector<int> vec{ 0,1,5,8,10,11};//有序数组
	vector<int>::iterator it1 = lower_bound(vec.begin(), vec.end(), 11);
	bool flag1 = it1 == vec.end() - 1;
	cout << flag1 << endl;//it1指向最后一个元素的迭代器
    unsigned i_lower = lower_bound(vec.begin(), vec.end(), 11) - vec.begin();
    cout << "i_lower:" << i_lower << endl;//位置5

	vector<int>::iterator it2 = upper_bound(vec.begin(), vec.end(), 11);
	bool flag2 = it2 == vec.end();
	cout << flag2 << endl;//it2为尾后迭代器
    unsigned j_upper = upper_bound(vec.begin(), vec.end(), 11) - vec.begin();
    cout << "j_upper:" << j_upper << endl;//位置6
	return 0;
}

运行结果

1
i_lower:5
1
j_upper:6

3) set集合(去重)

#include<algorithm>
#include<set>
using namespace std;

int main()
{
	set<int> s{ 0,2,5,8,11};//原本就有序
	set<int>::iterator it1 = s.lower_bound(2);
	cout << *it1 << endl;
	set<int>::iterator it2 = s.upper_bound(2);
	cout << *it2 << endl;
	return 0;
}

运行结果:

2
5

(3)map字典

#include<algorithm>
#include<map>
using namespace std;

int main()
{
	map<int, int> m{ {1,2},{2,2},{9,2},{7,2} };//有序
	map<int, int>::iterator it1 = m.lower_bound(2);
	cout << it1->first << endl;//it1->first=2
	map<int, int>::iterator it2 = m.upper_bound(2);
	cout << it2->first << endl;//it2->first=7;
	return 0;
}

运行结果:

2
7

参考:https://blog.csdn.net/weixin_42051815/article/details/115873582

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值