Detailed explanation of lower_bound() and upper_bound() (with source code)

lower_bound() and upper_bound() in STL

lower_bound() returns an iterator pointing to the first position where value can be inserted into the ordered sequence marked by [first,last) without breaking the container order, and this position marks the first value greater than or equal to value. And upper_bound() returns an iterator that points to the first position in the ordered sequence marked by [first,last) where value can be inserted without breaking the container order, and this position marks the first value greater than value. These two functions are functions in the C++ STL.

Simply put:
ForwardIter lower_bound(ForwardIter first, ForwardIter last, const _Tp& val) algorithm returns the first position in a non-decreasing sequence [first, last) that is greater than or equal to the value val.

The ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val) algorithm returns the first position in a non-decreasing sequence [first, last) greater than val.

As shown below:

write picture description here

Looking at the picture above, you can basically understand the usefulness of these two things.
Remember to add the header file ( #include<algorithm>) when you use it in the code

The STL library source code is posted below:

lower_bound():

//这个算法中,first是最终要返回的位置
int lower_bound(int *array, int size, int key)
{
    int first = 0, middle;
    int half, len;
    len = size;

    while(len > 0) {
        half = len >> 1;
        middle = first + half;
        if(array[middle] < key) {     
            first = middle + 1;          
            len = len-half-1;       //在右边子序列中查找
        }
        else
            len = half;            //在左边子序列(包含middle)中查找
    }
    return first;
}

upper_bound()

int upper_bound(int *array, int size, int key)
{
    int first = 0, len = size-1;
    int half, middle;

    while(len > 0){
        half = len >> 1;
        middle = first + half;
        if(array[middle] > key)     //中位数大于key,在包含last的左半边序列中查找。
            len = half;
        else{
            first = middle + 1;    //中位数小于等于key,在右半边序列中查找。
            len = len - half - 1;
        }
    }
    return first;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325817529&siteId=291194637