zoukankan      html  css  js  c++  java
  • [C++] upper_bound和lower_bound

    upper_bound 源码

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

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

    若val在原数组中存在,则upper_bound返回最后一个val的位置,lower_bound返回第一个val的位置
    若val在原数组中不存在,则upper_bound和lower_bound返回的都是val因放在哪个位置而不影响原序列

  • 相关阅读:
    angularjs $index用来取顺序
    angularjs &登录跳转
    if(!confirm("您确定删除吗?")){return;}
    登录跳转
    undefined null测试
    git生成密钥
    遍历map
    网络相关名词解释
    redis的Pub/Sub
    SQLAlchemy的使用
  • 原文地址:https://www.cnblogs.com/macinchang/p/4876183.html
Copyright © 2011-2022 走看看