STL——【lower_bound和upper_bound】

lower_bound和upper_bound

两个函数来源于algorithm库中

  • 未重载比较函数
    lower_bound是利用二分找出数组或者容器中第一个大于等于val的值对应的迭代器,而upper_bound是利用二分法找出数组或者容器中第一个大于val的值对应的迭代器。
    在STL源码中,两者的比较函数均为less<>,其中lower_bound的比较函数,二分的mid在前,val在后,此时可解释为:寻找第一个使得关系mid STL——【lower_bound和upper_bound】_第1张图片

STL——【lower_bound和upper_bound】_第2张图片

*重载比较函数后
lower_bound是找出第一个不满足比较函数的关系的迭代器,而upper_bound找出第一个满足比较函数关系的迭代器。
此处可以通过leetcode一个二分题目说明。其中对这个二分问题,分别重载了两个函数的比较函数,从而达到了二分的目的。值得注意的是,lower_bound与upper_bound中val位置的不同,其中lower_bound的val位置在后,而upper_bound的val位置在后。
STL——【lower_bound和upper_bound】_第3张图片
算法实现

class Solution {
public:
    int minEatingSpeed(vector<int>& piles, int h) {
        int left = 1;
        int right = *max_element(piles.begin(), piles.end());
        vector<int> ret_vec(right - left + 1);
        int k = -1;
        for (int i = left; i <= right; ++i)
            ret_vec[++k] = i;

        //int ret = *lower_bound(ret_vec.begin(), ret_vec.end(), h, [&](const int b, const int h) {
        //    int ret_b = 0;
        //    for (int pile : piles) {
        //        ret_b += (pile + b - 1) / b;
        //    }
        //    return h < ret_b;
        //    });

         int ret = *upper_bound(ret_vec.begin(), ret_vec.end(), h, [&](const int h, const int b){
             long ret_b = 0;
             for (int pile : piles) {
                 ret_b += (long)(pile + b - 1) / b;
             }
             return h >= ret_b;
         });
        return ret;
    }
};

你可能感兴趣的:(技术随笔,c++)