3 found at 3
//大理石在哪
#include
#include
using namespace std;
const int maxn = 10000;
int main()
{
int num, ques, x, a[maxn], kase = 0;
while(scanf("%d%d", &num, &ques) == 2 && num){
printf("CASE# %d:\n", ++kase);
for(int i = 0; i < num; i++)
scanf("%d", &a[i]);
sort(a, a+num); //排序
while(ques --){
scanf("%d", &x);
int p = lower_bound(a, a+num, x) - a; //在已排序数组a中找x
if(a[p] == x)
printf("%d found at %d\n", x, p+1);
else
printf("%d not found\n", x);
}
}
return 0;
}
主要学习了STL,然后就是 lower_bound( ) ;
int p = lower_bound(a, a+num, x) - a;
这段代码让我思考好一会,主要是因为忘了a是一个数组,
lower_bound( )返回的是一个迭代器,-a相当于减去a的首地址,返回的p即是它们之间的距离。
关于此函数的拓展使用:
一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标则(注:number为数组名)
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,所以返回最后一个元素的下一个元素)。