[STL]lower_bound

源码

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;
}

看起来就是个二分,不过有点奇怪

用途
"returns an iterator pointing to the first element in the range [first,last) which does not compare less than val."
返回一个序列中不小于val值的参数。注意该序列必须已经排序

参数
first, last
  Forward iterators to the initial and final positions of a sorted (or properly partitioned) sequence. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
  在一个已经排序的序列中传入起始和结束的迭代器。程序的范围为\([first,last)\),也就是说包含第一个迭代器指向的值,但不包含最后一个迭代器指向的值。
val
  Value of the lower bound to search for in the range.
  lowerbound要在范围内找的那个数
  For (1), T shall be a type supporting being compared with elements of the range [first,last) as the right-hand side operand of operator<.
  val的类型必须能和序列中的元素用\(<\)比较
comp
  Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, and the second, always val), and returns a value convertible to bool. The value returned indicates whether the first argument is considered to go before the second.
  返回值为bool的程序并且有两个参数(第一个值,第二个值)。返回第一个参数是否应该优先于第二个参数处理。其实就是判断小于
  The function shall not modify any of its arguments.
  这个函数不能修改仍和他的传入参数。显而易见
  This can either be a function pointer or a function object.
  珂以是一个函数的指针,也珂以是一个函数的实体

时间复杂度
Performs approximately \(log_2(N)+1\)

猜你喜欢

转载自www.cnblogs.com/linzhengmin/p/10893710.html