[C++复健日常] lower_bound()

hackerrank上复健了Lower Bound-STL
这道题 开始没注意他说用low_bound(), 然后就死磕了一番, 结果到后面就TLE了。(写的真的啰嗦不看也罢就是传统的按顺序遍历查询大了就break的那种哇塞这题还折腾了我好久老了老了
题目链接在这里:
Lower Bound-STL

(改用lower_bound()就很顺利啊(代码跳过重点在后面

就 还是要懂一下这个template是怎么操作的 看看官网怎么说
function template
std::lower_bound

default (1)	
template <class ForwardIterator, class T>
  ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,
                               const T& val);
custom (2)	
template <class ForwardIterator, class T, class Compare>
  ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,
                               const T& val, Compare comp);

Return iterator to lower bound
Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.
The elements are compared using operator< for the first version, and comp for the second. The elements in the range shall already be sorted according to this same criterion (operator< or comp), or at least partitioned with respect to val.
The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted range, which is specially efficient for random-access iterators.
Unlike upper_bound, the value pointed by the iterator returned by this function may also be equivalent to val, and not only greater.

The behavior of this function template is equivalent to

template <class ForwardIterator, class T>
  ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val)
{
  ForwardIterator it;
  iterator_traits<ForwardIterator>::difference_type count, step;
  count = distance(first,last);
  while (count>0)
  {
    it = first; step=count/2; advance (it,step);
    if (*it<val) {                 // or: if (comp(*it,val)), for version (2)
      first=++it;
      count-=step+1;
    }
    else count=step;
  }
  return first;
}

首先,要被查找的序列是有序的, 然后它返回的是一个不小于val(也就是第三个参数)的第一个元素的迭代器。然后它是二分法进行查找(是吧?

std::advance

template <class InputIterator, class Distance>
  void advance (InputIterator& it, Distance n);

Advance iterator:Advances the iterator it by n element positions. 经过一次advance,it就移动到step的位置也就是二分处,此时it的值就为first[step]

有两行代码稍微嘴一下(其实也没必要:
first=++it;it先自增1, 再赋值给first
count-=step+1;count = count - (step+1);

啊先这样 看完iteration和templates相关后再来补充
等等 既然底层是二分查找 那我为什么之前还在死磕???????

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值