• C++中lower_bound函数和upper_bound函数


    转载自:http://blog.csdn.net/niushuai666/article/details/6734403

    函数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的位置是越界的!!~

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

     1 #include <iostream>
     2 #include <algorithm>
     3 #include <functional>
     4 #include <vector>
     5 
     6 using namespace std;
     7 
     8 
     9 int main()
    10 {
    11     const int VECTOR_SIZE = 8 ;
    12 
    13     // Define a template class vector of int
    14     typedef vector<int > IntVector ;
    15 
    16     //Define an iterator for template class vector of strings
    17     typedef IntVector::iterator IntVectorIt ;
    18 
    19     IntVector Numbers(VECTOR_SIZE) ;
    20 
    21     IntVectorIt start, end, it, location ;
    22 
    23     // Initialize vector Numbers
    24     Numbers[0] = 4 ;
    25     Numbers[1] = 10;
    26     Numbers[2] = 11 ;
    27     Numbers[3] = 30 ;
    28     Numbers[4] = 69 ;
    29     Numbers[5] = 70 ;
    30     Numbers[6] = 96 ;
    31     Numbers[7] = 100;
    32 
    33     start = Numbers.begin() ;   // location of first
    34                                 // element of Numbers
    35 
    36     end = Numbers.end() ;       // one past the location
    37                                 // last element of Numbers
    38 
    39     // print content of Numbers
    40     cout << "Numbers { " ;
    41     for(it = start; it != end; it++)
    42         cout << *it << " " ;
    43     cout << " }
    " << endl ;
    44 
    45     // return the first location at which 10 can be inserted
    46     // in Numbers
    47     location = lower_bound(start, end, 1) ;
    48 
    49     cout << "First location element 10 can be inserted in Numbers is: "
    50         << location - start<< endl ;
    51 }
  • 相关阅读:
    《C语言》for语句(8)
    解决vue vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in nextTick: “TypeError: Cannot convert undefine
    React中WebSocket使用以及服务端崩溃重连
    React Native 中 react-navigation 导航器的使用 [亲测可用]
    ueditor 修改内容方法报错no funtion解决方式
    nodeJs与elementUI实现多图片上传
    Vue多页面开发案例
    Vue.js Cli 3.0 多页面开发案例解析
    基于node.js 微信支付notify_url回调接收不到xml
    react-image-gallery 加入视频图片混合显示
  • 原文地址:https://www.cnblogs.com/bfshm/p/4085874.html
Copyright © 2020-2023  润新知