1. lower_bound()和upper_bound()功能
lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序(“升序”)的数组中进行查找的。
1.1 lower_bound()
- 传入参数:lower_bound(begin, end, num)
- 函数含义:从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。
- 常用方法:
int pos=lower_bound(begin, begin+len, 7) - begin;
//返回数组中第一个大于或等于被查数的值的下标
- 重载lower_bound()
从大到小的数组也可以使用lower_bound(),只是一定要自定义比较函数。
lower_bound(a + 1, a + 1 + n, x, cmp);
bool cmp(const int& a,const int& b){return a > b;}
当然也可以直接
lower_bound(a + 1, a + 1 + n, x, greater <int> () );
2.1 upper_bound()
- 传入参数:upper_bound(begin, end, num)
- 函数含义:从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。
- 之后类似于1.1。