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

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

    测试代码如下:

    [cpp] view plaincopy
     
    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. }  
  • 相关阅读:
    串口速率问题
    java中byte short int的理解
    matlab 设置坐标轴的有效数字
    Tomcat闪退
    解决linux下sudo更改文件权限报错xxxis not in the sudoers file. This incident will be reported.
    Git的常用命令
    [原创]创建指定RowState属性的DataRow实例
    [转]中文VS2008中安装ASP.NET MVC框架出现问题的解决方法
    [转]JavaScript为事件处理器传递参数
    [转]LINQ to SQL(LINQ2SQL) vs. ADO.NET Entity Framework
  • 原文地址:https://www.cnblogs.com/szhan/p/3392219.html
Copyright © 2011-2022 走看看