STL——lower_bound()和upper_bound()

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值