二分检索函数lower_bound()和upper_bound()
二分检索函数lower_bound()和upper_bound()
一、说明
头文件:<algorithm>
二分检索函数lower_bound()和upper_bound()
lower_bound():找到大于等于某值的第一次出现
upper_bound():找到大于某值的第一次出现
必须从小到大排序后才能用
内部查找方式为二分查找,二分查找必定需要排序
返回值为地址
二、代码及结果
1 /* 2 二分检索函数lower_bound()和upper_bound() 3 lower_bound():找到大于等于某值的第一次出现 4 upper_bound():找到大于某值的第一次出现 5 必须从小到大排序后才能用 6 内部查找方式为二分查找,二分查找必定需要排序 7 返回值为地址 8 */ 9 #include <iostream> 10 #include <algorithm> 11 #include <string> 12 using namespace std; 13 14 15 int main(){ 16 17 int a[]={9,2,4,5,10,7,30}; 18 sort(a,a+7);//省略掉排序规则的形式,默认从小到大 19 //sort(a,a+7,less<int>());//用系统的排序规则,从小到大 20 //sort(a,a+7,greater<int>());//用系统的排序规则,从大到小 21 for(int i=0;i<7;i++){ 22 cout<<a[i]<<" "<<&a[i]<<endl; 23 } 24 cout<<endl; 25 /* 26 这个lower_bound要从小到大排序才正确, 27 如果是从大到小,或者不排序,还是输出的从小到大排序好后的位置 28 */ 29 int *p=lower_bound(a,a+7,2);//用lower_bound找大于等于2的第一次出现 30 cout<<p<<endl; 31 cout<<*p<<endl; 32 int *p1=upper_bound(a,a+7,2);//用upper_bound找大于等于2的第一次出现 33 cout<<p1<<endl; 34 cout<<*p1<<endl; 35 36 37 38 return 0; 39 }

版权申明:欢迎转载,但请注明出处
一些博文中有一些参考内容因时间久远找不到来源了没有注明,如果侵权请联系我删除。
在校每年国奖、每年专业第一,加拿大留学,先后工作于华东师范大学和香港教育大学。
2025-04-30:宅加太忙,特此在网上找女朋友,坐标上海,非诚勿扰,vx:fan404006308
AI交流资料群:753014672

浙公网安备 33010602011771号