C/C++-STL中lower_bound与upper_bound的用法以及cmp函数


转载于:http://blog.csdn.net/tjpuacm/article/details/26389441

 

不加比较函数的情况:

 

[cpp]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. int a[]={0,1,2,2,3};  
  2. printf("%d\n",lower_bound(a,a+5,2,cmp)-a);  
  3. printf("%d\n",upper_bound(a,a+5,2,cmp)-a);  


结果:2 4

 

lower的意义是对于给定的已经排好序的a,key最能插入到那个位置

0 1 | 2 2 3 所以2最插入到2号位置

upper的意义是对于给定的已经排好序的a,key最能插入到那个位置

0 1 2 2 | 3 所以2最插入到4号位置

加了比较函数:

 

[cpp]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. bool cmp(int a,int b)  
  2. {  
  3.     return a<b;  
  4. }  
  5. int main()  
  6. {  
  7.     int a[]={0,1,2,2,3};  
  8.     printf("%d\n",lower_bound(a,a+5,2,cmp)-a);  
  9.     printf("%d\n",upper_bound(a,a+5,2,cmp)-a);  
  10.     return 0 ;  
  11. }  


结果仍然是2 4 ,可以得出一个结论,cmp里函数应该写的是小于运算的比较

 

如果加上了等号,lower和upper两个函数功能就刚好反过来了:

 

[cpp]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. bool cmp(int a,int b)  
  2. {  
  3.     return a<=b;  
  4. }  
  5. int main()  
  6. {  
  7.     int a[]={0,1,2,2,3};  
  8.     printf("%d\n",lower_bound(a,a+5,2,cmp)-a);  
  9.     printf("%d\n",upper_bound(a,a+5,2,cmp)-a);  
  10.     return 0 ;  
  11. }  


结果是4 2


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM