STL_lower_bound&upper_bound用法

ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置。

     ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)算法返回一个非递减序列[first, last)中第一个大于val的位置。

下面是这两个功能的实现:

 1 #include <iostream>
 2 #include <cstdio>
 3 
 4 using namespace std;
 5 
 6 int my_lower_bound(int array[],int len,int t){
 7     int s=0,e=len-1;
 8     int mid;
 9     int ans;
10     while(s<e){
11         mid=(s+e)/2;
12         if(array[mid]>=t){
13             e=mid;
14             ans=e;
15         }else{
16             s=s+1;;
17             ans=s;
18         }
19     }
20     return ans;
21 }
22 
23 int my_upper_bound(int array[],int len,int t){
24     int s=0,e=len-1;
25     int mid;
26     int ans;
27     while(s<e){
28         mid=(s+e)/2;
29         if(array[mid]<=t){
30             s+=1;
31             ans=s;
32         }else{
33             e=mid;
34             ans=e;
35         }
36     }
37     return ans;
38 }
39 
40 int main()
41 {
42     int a[10]={1,2,2,3,4,4,4,4,5,6};
43     int l=my_lower_bound(a,10,4);//数值4
44     int u=my_upper_bound(a,10,4);//数值5
45     printf("%d %d",a[l],a[u]);
46     return 0;
47 }

 

posted @ 2016-10-23 20:59  多一份不为什么的坚持  阅读(466)  评论(0编辑  收藏  举报