STL 二分查詢

2022-05-02 04:51:07 字數 993 閱讀 5730

實現原始碼:

1.在乙個遞增的陣列(或vector)中查詢元素屬於[ s , e ) 的下標

2.查詢遞增陣列中元素是否存在

使用binary_search

注:

對於結構體,要麼過載小於符號:

①bool operator

②要麼定義有小於符號含義的cmp函式。

3.應用在遞減序列中

#include#include

#include

using

namespace

std;

bool cmp(int x,int

y)int

main();

int desc[10]=;

int obj=8

;

int p1=upper_bound(asc,asc+10,obj)-asc;

int p2=upper_bound(desc,desc+10,obj,cmp)-desc;

printf(

"%d,%d\n

",p1,p2) ;

return0;

}

view code

stl 二分查詢

在stl中對二分查詢進行了封裝,有兩種 upper bound,lower bound。例如 pos lower bound a,a n,value 查詢value值在長度為n的陣列a中的位置 關於返回值,函式lower bound 在first和last中的前閉後開區間進行二分查詢,返回大於或等於...

二分搜尋與STL二分查詢

用法 搜尋非遞減數列中是否包含某個元素 當資料量比較大的時候,二分比線性搜尋高效得多。流程 查詢36 實現 物件是非遞減序列,如果當資料無序時,需要預先進行一次排序。int binarysearch int a,int key,int n n為陣列長度 rerurn 0 陣列a中不存在key 複雜度...

STL中二分查詢

偶然遇到了一些問題,記錄一下 標頭檔案 include 1.binary search 查詢某個元素是否出現。函式原型 bool lower bound forwarditer first,forwarditer last,const tp val 函式功能 在陣列中以二分法檢索的方式查詢,若在陣列...