lower_bound头文件
时间: 2023-10-29 20:00:22 浏览: 47
lower_bound()和upper_bound()函数是C++ STL标准库中的查找函数,它们的底层实现采用二分查找的方式。在使用这两个函数之前,需要添加<algorithm>头文件。
示例代码如下:
```
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
const int n = 6;
int arr[n]{ 0,1,5,8,10,11};
int i_lower = lower_bound(arr, arr+n, 8) - arr; // 返回大于等于8的元素的地址
int i_upper = upper_bound(arr, arr+n, 8) - arr; // 返回大于8的元素的地址
cout << "i_lower:" << i_lower << endl; // i_lower:3
cout << "i_upper:" << i_upper << endl; // i_upper:4
int j_lower = lower_bound(arr, arr+n, 10) - arr;
int j_upper = upper_bound(arr, arr+n, 10) - arr;
cout << "j_lower:" << j_lower << endl; // j_lower:4
cout << "j_upper:" << j_upper << endl; // j_upper:5
return 0;
}
```
请注意,lower_bound()函数返回的是第一个大于等于目标值的元素的地址,而upper_bound()函数返回的是第一个大于目标值的元素的地址。因此,通过减去数组的起始地址,可以得到相应的索引位置。