#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 10000;
int main()
{
int n, q, x, a[maxn], kase = 0;
while(cin >> n >> q && n){
cout << "CASE# " << ++kase << ":" << endl;
for(int i = 0; i < n; i++) cin >> a[i];
sort(a, a+n);
while(q--){
cin >> x;
int p = lower_bound(a, a+n, x) - a;
if(a[p] == x) cout << x << " found at " << p+1 << endl;
else cout << x << " not found\n";
}
}
return 0;
}
lower_bound从数组中寻找x,返回找到的指针
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 10000;
int main()
{
int n, q, kase = 0, x, a[maxn];
while(scanf("%d%d",&n,&q) == 2 && n){
printf("CASE# %d:\n",++kase);
for(int i = 0; i < n; i++) scanf("%d",&a[i]);
sort(a, a+n);
for(int i = 0; i < q; i++){
scanf("%d", &x);
int p = lower_bound(a, a+n, x) - a;
if(a[p] == x) printf("%d found at %d\n",x,p+1);
else printf("%d not found\n",x);
}
}
return 0;
}
本文详细介绍了如何在C++中利用lower_bound函数从数组中查找特定值,并输出该值在数组中的位置。通过实例演示了数组排序和lower_bound函数的应用,适合C++初学者和中级开发者。
1015

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



