zoukankan      html  css  js  c++  java
  • lower_bound()学习

    函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置

    举例如下:

    一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标

    pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number数组的下标为0的位置。

    pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number数组的下标为1的位置(即10所在的位置)。

    pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)。

    所以,要记住:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!~

    返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置

    #include<iostream>
    #include<algorithm>
    #include<functional>
    #include<vector>
    
    using namespace std;
    
    int main(){
        vector<int> numbers(8);
        vector<int>::iterator start,end,it,location;
    
        numbers[0] = 4 ;
        numbers[1] = 10;
        numbers[2] = 11 ;
        numbers[3] = 30 ;
        numbers[4] = 69 ;
        numbers[5] = 70 ;
        numbers[6] = 96 ;
        numbers[7] = 100;
    
        start=numbers.begin();
        end=numbers.end();
    
        cout<<"numbers :{";
        for(it=start;it!=end;it++)
            cout<<*it<<" ";
        cout<<"}"<<endl;
    
        location=lower_bound(start,end,9);
        cout << "First location element 9 can be inserted in Numbers is: ";
        cout<< location - start<< endl ;
    
    
        return 0;
    }
  • 相关阅读:
    iOS开发tips-UITableView、UICollectionView行高/尺寸自适应
    10559
    日志系统之基于Zookeeper的分布式协同设计
    IOS 图片上传处理 图片压缩 图片处理
    istream, outstream使用及常见错误
    matlab 扩大虚拟内存
    github不小心同步覆盖了本地文件
    经典统计语言模型
    Makefile 快速入门
    word2vec——高效word特征提取
  • 原文地址:https://www.cnblogs.com/jackge/p/2842923.html
Copyright © 2011-2022 走看看