C++ lower_bound Function: Purpose & Usage Guide
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 specified value. More specifically, the lower_bound function returns an iterator pointing to the first element in the sequence that is not less than the specified value.
Here is how to use the lower_bound function:
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 查找第一个大于等于3的元素的位置
auto it = std::lower_bound(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
std::cout << "第一个大于等于3的元素的位置为:" << std::distance(vec.begin(), it) << std::endl;
}
return 0;
}
In the example above, the lower_bound function will return an iterator pointing to the element 3. In this case, 3 is the first element greater than or equal to 3, so the output is “The position of the first element greater than or equal to 3 is: 2”.