lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序的数组中进行查找的。
在从小到大的排序数组中,
lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
在从大到小的排序数组中,重载lower_bound()和upper_bound()
lower_bound( begin,end,num,greater() ):从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num,greater() ):从数组的begin位置到end-1位置二分查找第一个小于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[100]={1,2,4,4,9,12,12,15};//假定一个数组
int pos1 = lower_bound(a,a+8,4)-a;//返回查找到的第一个等于4的下标
int pos2 = upper_bound(a,a+8,4)-a;//返回查找到的最后一个等于4的下标
cout <<"pos1 is "<<pos1<<endl;
cout <<"pos2 is "<<pos2<<endl;
/*
//vector
vector<int> a;
vector<int>::iterator p;
p = lower_bound(b.begin(),b.end(),4);
cout <<"result is "<<*p<<endl; //*p所指的就是找到的p所指的元素的值
*/
//set
/*
set<int> a;
set<int>::iterator p;
p = a.lower_bound(value);//value即为要查找的值
*/
return 0;
}