lower_bound()和upper_bound()这两个函数都是利用二分查找的方法在一个有序数组中进行查找。
基本使用方法:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int a[10] = {20, 21, 23, 24, 27, 28, 30, 32, 35, 38};
int pos;
//第一个>=24的数字是24,下标为[3]
pos = lower_bound(a, a + 10, 24) - a;
cout << pos << endl;
//第一个>24的数字是27,下标为[4]
pos = upper_bound(a, a + 10, 24) - a;
cout << pos << endl;
//未找到,下标为[10](溢出),值为10
pos = lower_bound(a, a + 10, 123) - a;
cout << pos << endl;
return 0;
}
运行结果:
3
4
10
在有序数组(递增)中插入元素仍保持有序:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<int> v;
for(int i = 30; i < 60; i += 3)
v.push_back(i); //元素分别为30,33,36,...,54,57
int insertValue = 37;
//查找第一个>=insertValue的元素的位置
vector<int>::iterator pos = lower_bound(v.begin(), v.end(), insertValue);
v.insert(pos, insertValue); //在查到的位置插入insertValue
for(int i = 0; i < v.size(); i++)
cout << v[i] << " ";
return 0;
}
运行结果:
30 33 36 37 39 42 45 48 51 54 57
在有序数组(递减)中插入元素仍保持有序:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v;
for(int i = 60; i > 30; i -= 3)
v.push_back(i); //元素分别为57,54,51,...,36,33
int insertValue = 37;
//查找第一个<=insertValue的元素的位置
vector<int>::iterator pos = lower_bound(v.begin(), v.end(), insertValue, greater<int>());
v.insert(pos, insertValue); //在查到的位置插入insertValue
for(int i = 0; i < v.size(); i++)
cout << v[i] << " ";
return 0;
}
运行结果:
60 57 54 51 48 45 42 39 37 36 33
二分法查找代码本身不难实现,但如果熟练使用这两个函数,在编写“在有序序列中查找元素”的时候往往会起到事半功倍的效果。
氷鸢鸢鸢
2020.7.19