stl_algorithm算法之二分法查找

Posted _xiaohaige

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了stl_algorithm算法之二分法查找相关的知识,希望对你有一定的参考价值。

二分法查找:

技术分享
7.60、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;
}
技术分享

 

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

 

技术分享
7.62、template <class ForwardIterator, class T>
pair<ForwardIterator,ForwardIterator>
equal_range (ForwardIterator first, ForwardIterator last, const T& val)
{
  ForwardIterator it = std::lower_bound (first,last,val);
  return std::make_pair ( it, std::upper_bound(it,last,val) );
}
技术分享
7.63、template <class ForwardIterator, class T>
bool binary_search (ForwardIterator first, ForwardIterator last, const T& val)
{    
  first = std::lower_bound(first,last,val);
  return (first!=last && !(val<*first));
}

以上是关于stl_algorithm算法之二分法查找的主要内容,如果未能解决你的问题,请参考以下文章

stl_algorithm算法之融合算法

stl_algorithm算法之排序算法

stl_algorithm算法之变动性算法和非动性算法

stl_algorithm算法之Max/Min算法

python算法之二分查找

算法之二分查找PK线性查找