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