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