lowerbound和upperbound
时间: 2024-04-01 08:30:18 浏览: 20
lower_bound()和upper_bound()是C++ STL标准库中的两个函数,用于在一个已排序的数组中进行查找。它们都使用二分查找算法来实现查找操作[^1]。
lower_bound()函数返回一个迭代器,指向数组中第一个大于或等于给定值的元素。如果数组中不存在大于或等于给定值的元素,则返回指向数组末尾的迭代器。下面是lower_bound()函数的示例代码:
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 6;
auto it = std::lower_bound(nums.begin(), nums.end(), target);
if (it != nums.end()) {
std::cout << "Lower bound of " << target << " is " << *it << std::endl;
} else {
std::cout << "No lower bound found" << std::endl;
}
return 0;
}
```
输出结果为:
```
Lower bound of 6 is 6
```
upper_bound()函数返回一个迭代器,指向数组中第一个大于给定值的元素。如果数组中不存在大于给定值的元素,则返回指向数组末尾的迭代器。下面是upper_bound()函数的示例代码:
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 6;
auto it = std::upper_bound(nums.begin(), nums.end(), target);
if (it != nums.end()) {
std::cout << "Upper bound of " << target << " is " << *it << std::endl;
} else {
std::cout << "No upper bound found" << std::endl;
}
return 0;
}
```
输出结果为:
```
Upper bound of 6 is 7
```