头文件:#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;
}
本文介绍C++ STL中的lower_bound函数使用方法,通过一个查找数组中元素的具体例子,展示了如何利用lower_bound定位待插入元素的位置,并提供了一个完整的程序实现。

862

被折叠的 条评论
为什么被折叠?



