lower_bound()返回值

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

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


测试代码如下:

[cpp]  view plain copy
  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 << " }\n" << 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. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值