紫书 p108 例题5-1

lower_bound(a,a+n,x):查找“大于或等于x的第一个元素”调用lower_bound之前必须确定序列为有序序列,否则调用出错。返回一个迭代器。

sort,可以是普通数组sort(a,a+n);vector:sort(v.begin(),v.end())

#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn=10000;

int main()
{
    int N,Q,i,q,a[maxn],kase=0,p;
    while(scanf("%d%d",&N,&Q)!=EOF)
    {
        if(N==0)break;
        printf("CASE# %d:\n",++kase);
        for(i=0;i<N;i++)scanf("%d",&a[i]);
        sort(a,a+N);
        while(Q--)
        {
            scanf("%d",&q);
            p=lower_bound(a,a+N,q)-a;
            if(a[p]==q)printf("%d found at %d\n",q,p+1);
            else printf("%d not found\n",q);
        }
    }
    return 0;
}































版权声明:本文为mtxxxx原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。