zoukankan      html  css  js  c++  java
  • stl lower_bound upper_bound binary_search equal_range

    自己按照stl实现了一个:

     

    http://www.cplusplus.com/reference/algorithm/binary_search/ 这里有个注释,如何判断两个元素相同:

    Two elements, a and bare considered equivalent if (!(a<b) && !(b<a))

    lower_bound返回!(*it<val) ,所以binary_search 只要再判断 !(val<*it) 即可。

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

    #include<cstdio>
    #include<iostream>
    #include<string>
    #include<algorithm>
    #include<iterator>
    #include<sstream>//istringstream
    #include<cstring>
    
    
    using namespace std;
    
    //return first element >=
    
    int * lowerbound(int *first, int* last, int value)
    {
        int* it;
        int count=last-first;
        int step;
        while(count>0)
        {
            it=first;
            step=count/2;
            it+=step;
            //it指向的<, ++后排除<
            if(*it<value)
            {
                first=++it;
                count-=step+1;
            }
            else//左边
                count=step;
    
        }
        return first;
    }
    
    //return first element >
    int* upperbound(int *first, int *last, int value)
    {
        int count=last-first;
        int step;
        int *it;
        while(count>0)
        {
            step=count/2;
            it=first+step;
            //it指向 <= ,++后排除<=
            if(!(value<*it))
            {
                first=++it;
                count-=step+1;
            }
            else
            {
                count=step;
            }
        }
        return first;
    }
    
    int main()
    {
        int a[]={ 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6 };
        int *lb=lowerbound(a, a+sizeof(a)/sizeof(int), 4);
        cout<<*lb<<endl;
    
        int *ub=upperbound(a, a+sizeof(a)/sizeof(int), 4);
        cout<<*ub<<endl;
        return 0;
    }
  • 相关阅读:
    java对象转json对象
    cas-client登录后报INVALID_PROXY_CALLBACK
    tomcat启动一闪而过,调试tomcat
    获取url中的参数
    cas 退出后跳转指定页面
    cas增加验证码
    spring security+cas(cas proxy配置)
    oracle 导入导出指定表
    Marshaller根据对象生成xml文件
    webpack学习笔记
  • 原文地址:https://www.cnblogs.com/cute/p/3620886.html
Copyright © 2011-2022 走看看