STL upper_bound(),lower_bound()函数的学习+自己的实现

时间:2022-09-28 17:57:09

STL里,这两个函数用于在有序的数组里找某个元素的位置,用法简单提一下upper_bound(begin,end,key),start是查找的起点,end是终点,key是关键值,lower_bound()用法一样,upper_bound()函数,返回第一个大于要找的值得位置(或者理解是这个元素的下一个位置),而Lower_bound是小于等于关键字的位置(或者理解为关键字第一次出现 的位置),

#include<bits/stdc++.h>
using namespace std;
const int maxn=2222;
int a[maxn];
int n;
int my_upper_bound(int num)
{
int l=0;
int h=n-1;
while(l<=h)
{
int mid=(l+h)/2;
if(num<a[mid])
h=mid-1;
else
l=mid+1;
}
return l;
}
int my_lower_bound(int num)
{
int l=0;
int h=n-1;
while(l<=h)
{
int mid=(l+h)/2;
if(num>a[mid])
l=mid+1;
else
h=mid-1;
}
return l;
}

int main()
{
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
printf("my_upper_bound(4) 位置在 %d\n",my_upper_bound(4));
printf("my_lower_bound(4) 位置在 %d\n",my_lower_bound(4));
printf("lower_bound(4) 位置在 %d\n",lower_bound(a,a+n,4)-a);
printf("upper_bound(4) 位置在 %d\n",upper_bound(a,a+n,4)-a);
return 0;
}
STL upper_bound(),lower_bound()函数的学习+自己的实现