C++ lower_bound Function: Complete Guide

In C++, the lower_bound function is used to return the position of the first element in a sorted range that is not less than the given value.

Here is the syntax for the lower_bound function:

std::vector<int>::iterator lower_bound (std::vector<int>::iterator first, std::vector<int>::iterator last, const int& val);

Before using the lower_bound function, make sure that the interval has been sorted in ascending order. Then, pass three parameters to the function: an iterator pointing to the beginning of the interval, an iterator pointing to the end of the interval, and the value to be searched for.

The lower_bound function searches for the first element in the specified range that is not less than the given value val, and returns an iterator pointing to that element. If no element meeting the condition is found, it returns an iterator pointing to the end of the range.

Here is a simple example code demonstrating how to use the lower_bound function.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    // 查找不小于 5 的第一个元素的位置
    std::vector<int>::iterator it = std::lower_bound(vec.begin(), vec.end(), 5);

    if (it != vec.end()) {
        std::cout << "第一个不小于5的元素位置为:" << std::distance(vec.begin(), it) << std::endl;
    } else {
        std::cout << "未找到符合条件的元素" << std::endl;
    }

    return 0;
}

In the example above, the lower_bound function is used to find the first element in vec that is not less than 5. Since vec is already sorted in ascending order, the iterator returned points to 5.

bannerAds