function for finding last item less-than-or-equal to, like lower_bound

前端 未结 5 1791
南方客
南方客 2021-01-30 12:52

Is there a function in that uses binary search, like lower_bound but that returns the last item less-than-or-equal-to according to a given predic

5条回答
  •  故里飘歌
    2021-01-30 13:34

    Here is a wrapper function around upper_bound which returns the largest number in a container or array which is less than or equal to a given value:

    template 
      ForwardIterator largest_less_than_or_equal_to ( ForwardIterator first, 
                                                      ForwardIterator last,
                                                      const T& value)
    {
      ForwardIterator upperb = upper_bound(first, last, value);
    
      // First element is >, so none are <=
      if(upperb == first)
        return NULL;
    
      // All elements are <=, so return the largest.
      if(upperb == last)
        return --upperb;
    
      return upperb - 1;
    }
    

    For a better explanation of what this is doing and how to use this function, check out:

    C++ STL — Find last number less than or equal to a given element in an array or container

提交回复
热议问题