二分检索函数lower_bound()和upper_bound()
生活随笔
收集整理的這篇文章主要介紹了
二分检索函数lower_bound()和upper_bound()
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
二分檢索函數(shù)lower_bound()和upper_bound()
一、說明
頭文件:<algorithm>
二分檢索函數(shù)lower_bound()和upper_bound()
lower_bound():找到大于等于某值的第一次出現(xiàn)
upper_bound():找到大于某值的第一次出現(xiàn)
必須從小到大排序后才能用
內(nèi)部查找方式為二分查找,二分查找必定需要排序
返回值為地址
?
二、代碼及結(jié)果
1 /* 2 二分檢索函數(shù)lower_bound()和upper_bound() 3 lower_bound():找到大于等于某值的第一次出現(xiàn) 4 upper_bound():找到大于某值的第一次出現(xiàn) 5 必須從小到大排序后才能用 6 內(nèi)部查找方式為二分查找,二分查找必定需要排序 7 返回值為地址 8 */ 9 #include <iostream> 10 #include <algorithm> 11 #include <string> 12 using namespace std; 13 14 15 int main(){ 16 17 int a[]={9,2,4,5,10,7,30}; 18 sort(a,a+7);//省略掉排序規(guī)則的形式,默認(rèn)從小到大 19 //sort(a,a+7,less<int>());//用系統(tǒng)的排序規(guī)則,從小到大 20 //sort(a,a+7,greater<int>());//用系統(tǒng)的排序規(guī)則,從大到小 21 for(int i=0;i<7;i++){ 22 cout<<a[i]<<" "<<&a[i]<<endl; 23 } 24 cout<<endl; 25 /* 26 這個(gè)lower_bound要從小到大排序才正確, 27 如果是從大到小,或者不排序,還是輸出的從小到大排序好后的位置 28 */ 29 int *p=lower_bound(a,a+7,2);//用lower_bound找大于等于2的第一次出現(xiàn) 30 cout<<p<<endl; 31 cout<<*p<<endl; 32 int *p1=upper_bound(a,a+7,2);//用upper_bound找大于等于2的第一次出現(xiàn) 33 cout<<p1<<endl; 34 cout<<*p1<<endl; 35 36 37 38 return 0; 39 }?
轉(zhuǎn)載于:https://www.cnblogs.com/Renyi-Fan/p/6961035.html
總結(jié)
以上是生活随笔為你收集整理的二分检索函数lower_bound()和upper_bound()的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [floyd+路径输出]HDU1385
- 下一篇: xcode5. 安装cocos2d-x