码迷,mamicode.com
首页 > 编程语言 > 详细

stl_algorithm算法之二分法查找

时间:2017-05-01 13:35:15      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:tle   技术分享   equal   ++i   copy   blog   code   tool   trait   

二分法查找:

技术分享
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算法之二分法查找

标签:tle   技术分享   equal   ++i   copy   blog   code   tool   trait   

原文地址:http://www.cnblogs.com/xiaohaige/p/6791725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!