c语言lower_bound
时间: 2024-03-15 19:39:57 浏览: 15
在C语言中,lower_bound是一个用于在有序数组中查找某个元素的函数。它返回的是大于或等于给定值的第一个元素的指针。
下面是lower_bound函数的原型:
```c
#include <stdio.h>
#include <stdlib.h>
int* lower_bound(int* first, int* last, int value);
```
参数说明:
- `value`:要查找的值
返回值:
- 如果找到了大于或等于给定值的元素,则返回该元素的指针
- 如果没有找到大于或等于给定值的元素,则返回last指针
下面是一个示例代码,演示了如何使用lower_bound函数:
```c
#include <stdio.h>
#include <stdlib.h>
int* lower_bound(int* first, int* last, int value) {
while (first < last) {
int* mid = first + (last - first) / 2;
if (*mid < value) {
first = mid + 1;
} else {
last = mid;
}
}
return first;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int value = 3;
int* result = lower_bound(arr, arr + n, value);
if (result != arr + n) {
printf("找到了大于或等于%d的第一个元素:%d\n", value, *result);
} else {
printf("没有找到大于或等于%d的元素\n", value);
}
return 0;
}
```
输出结果:
```
找到了大于或等于3的第一个元素:3
```