How do you use the lower_bound function in C++?
In C++, the lower_bound function is used to find the position of the first element in a sorted sequence that is not less than a given value. Its syntax is as follows:
template <class ForwardIterator, class T>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val);
In this case, “first” and “last” are iterators that represent a range, and “val” is the value to be found. The lower_bound function returns an iterator pointing to the first element position that is greater than or equal to “val.”
Here is an example of using the lower_bound function:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 6;
std::vector<int>::iterator it = std::lower_bound(nums.begin(), nums.end(), target);
if (it != nums.end() && *it == target) {
std::cout << "找到了目标元素:" << *it << std::endl;
} else {
std::cout << "未找到目标元素" << std::endl;
}
return 0;
}
In the example above, we created a sorted vector called nums and used the lower_bound function to search for the element with a value of 6. The lower_bound function returns an iterator that points to the first position greater than or equal to 6, which is 6 itself. We then check if the element pointed to by the iterator is equal to the target value of 6, and if it is, this means we have found the target element.
The output is: Found the target element: 6.