思路
lower_bound() 包含algorithm头文件
a[i] : 1, 3, 5, 7, 9
pos = lower_bound(a, a + n, x) - a;
x = 0, pos = 0;
x = 1, pos = 1;
x = 9, pos = 4;
x = 10, pos = 5;
即lower_bound() return 第一个 >= 指定元素的位置
拓展
- upper_bound() 更多…
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e4 + 10;
int n, m;
int a[N];
int main()
{
int cnt = 1;
while(cin >> n >> m, n || m)
{
printf("CASE# %d:\n", cnt ++ );
for(int i = 0; i < n; i ++ )
cin >> a[i];
sort(a, a + n);
while(m -- )
{
int x;
cin >> x;
int pos = lower_bound(a, a + n, x) - a;
if(a[pos] == x)
printf("%d found at %d\n", x, pos + 1);
else
printf("%d not found\n", x);
}
}
return 0;
}