zoukankan      html  css  js  c++  java
  • C++ 二分查找函数 lower_bound upper_bound

    lower_bound

      (ForwardIterator first, ForwardIterator last,const T& val)

      (ForwardIterator first, ForwardIterator last,const T& val, Compare cmp)

      返回一个 指向 [first,last) 中第一个大于等于 数val的 iterator。

    upper_bound

      (ForwardIterator first, ForwardIterator last,const T& val)

      (ForwardIterator first, ForwardIterator last,const T& val, Compare cmp)

      返回一个 指向 [first,last) 中第一个大于 数val的 iterator。

    用法示例:
    #include <iostream>
    #include <algorithm>
    using namespace std;
    int a[100];
    int d[100];
    const int INF = 0x3f3f3f3f;
    int main(){
        int n;
        int num[] = {1,5,2,6,8,1,2,5};
        sort(num,num+sizeof(num)/sizeof(int));// 1 1 2 2 5 5 6 8
        int pos1 = lower_bound(num,num+8,8) - num;//返回数组中第一个大于或等于被查数的下标位置 
        int pos2 = upper_bound(num,num+8,8) - num;//返回数组中第一个大于被查数的下标位置 
        cout << pos1 << " " << pos2 << endl;
        sort(num,num+sizeof(num)/sizeof(int),greater<int>());//8 6 5 5 2 2 1 1
        //如果从小到大排序,除非查找不到返回8,否则都返回0,没有意义。 
        pos1 = lower_bound(num,num+8,-1,greater<int>()) - num;//返回数组中第一个小于或等于被查数的下标位置 
        pos2 = upper_bound(num,num+8,8,greater<int>()) - num;//返回数组中第一个小于被查数的下标位置 
        cout << pos1 << " " << pos2 << endl;
        return 0;
    }
  • 相关阅读:
    全国城市经纬度
    CentOS下SSH无密码登录的配置
    Nginx 1.9+PHP5.6 环境搭建
    Sphinx 2.2.11-release reference manual
    JVM 内存管理机制
    solr 3.5.0 与 tomcat 7.0.5 整合配置
    lucene 分词实现
    lucene 索引 demo
    lucene 搜索demo
    Lucene 简单API使用
  • 原文地址:https://www.cnblogs.com/--zz/p/10571596.html
Copyright © 2011-2022 走看看