您的位置:首页 > 编程语言 > C语言/C++

C++ STL 之 lower_bound and upper_bound

2017-10-25 18:14 471 查看
头文件:#include< algorithm >

1.lower_bound (first, last, const_val)

返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置

2.upper_bound(first, last, const_val)

返回大于val的第一个元素位置。如果所有元素都小于val,则返回last的位置

举例如下:

一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标



pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number数组的下标为0的位置。

pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number数组的下标为1的位置(即10所在的位置)。

pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)。

//uva10474
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=10000;
int main()
{
int arr[maxn],n,q,x,i,p,count=0;
while(scanf("%d %d",&n,&q)==2&& n)
{
printf("CASE# %d:\n",++count);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
sort(arr,arr+n);
while(q--)
{
scanf("%d",&x);
p=lower_bound(arr,arr+n,x)-arr;
if(arr[p]==x) printf("%d found at %d\n",x,p+1);
else printf("%d not found\n",x);

}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: