lower_bound
时间: 2023-10-14 08:13:30 浏览: 63
lower-bound函数.md
The lower_bound() function is a built-in C++ function that returns an iterator pointing to the first element in a sorted range that is not less than a given value. It is defined in the <algorithm> header file.
Syntax:
```
template <class ForwardIterator, class T>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val);
```
Here, first and last are iterators that define the range to be searched, and val is the value to be compared with the elements in the range.
The lower_bound() function works only on sorted ranges. It uses a binary search algorithm to find the first element that is not less than val. If such an element is found, it returns an iterator to that element. If no such element is found, it returns an iterator to the end of the range.
Example:
```
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> v {1, 3, 5, 7, 9};
auto it = std::lower_bound(v.begin(), v.end(), 6);
if (it != v.end()) {
std::cout << "The first element not less than 6 is " << *it << '\n';
} else {
std::cout << "No element not less than 6 was found\n";
}
return 0;
}
```
Output:
```
The first element not less than 6 is 7
```
阅读全文