二分检索函数lower_bound()和upper_bound()
lower_bound():找到大于等于某值的第一次出现
upper_bound():找到大于某值的第一次出现
必须从小到大排序后才能用
内部查找方式为二分查找,二分查找必定需要排序
返回值为地址
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;int main(){int a[]={9,2,4,5,10,7,30};sort(a,a+7);//省略掉排序规则的形式,默认从小到大 //sort(a,a+7,less<int>());//用系统的排序规则,从小到大 //sort(a,a+7,greater<int>());//用系统的排序规则,从大到小 for(int i=0;i<7;i++){cout<<a[i]<<" "<<&a[i]<<endl;}cout<<endl; /*这个lower_bound要从小到大排序才正确,如果是从大到小,或者不排序,还是输出的从小到大排序好后的位置 */int *p=lower_bound(a,a+7,2);//用lower_bound找大于等于2的第一次出现 cout<<p<<endl; cout<<*p<<endl; int *p1=upper_bound(a,a+7,2);//用upper_bound找大于等于2的第一次出现cout<<p1<<endl; cout<<*p1<<endl;return 0;
}
/*输出:
2 0x70fe00
4 0x70fe04
5 0x70fe08
7 0x70fe0c
9 0x70fe10
10 0x70fe14
30 0x70fe180x70fe00
2
0x70fe04
4
*/