STL中的二分查詢(binary search)

2021-06-06 08:45:07 字數 1606 閱讀 2718

stl中對於有序序列(vector,list等)提供了相當相當強大的二分搜尋binary search演算法。對於可以隨機訪問容器(如vector等),binary search負載度為對數級別(logn),對於非隨機訪問容器(如list),則演算法複雜度為線性。現在簡要介紹一下幾種常用的binary search演算法:

iterator lower_bound (iterator first,iterator last, const t& value)

iterator lower_bound (iterator first,iterator last, const t& value, compare comp)

//返回乙個迭代器,指向鍵值》=value的第乙個元素

iterator upper_bound (iterator first,iterator last, const t& value)

iterator upper_bound (iterator first,iterator last, const t& value, compare comp)

//返回乙個迭代器,指向鍵值》value的第乙個元素(注意此處與上乙個的區別).

pair equal_range(iterator first, iterator last, const t& value)

pair equal_range(iterator first, iterator last, const t& value, compare comp)

//試圖在已排序的[first,last)中尋找value,它返回一對迭代器i和j,其中i是在不破壞次序的前提下,value可插入的第乙個位置(亦即lower_bound),j則是在不破壞次序的前提下,value可插入的最後乙個位置(亦即upper_bound),因此,[i,j)內的每個元素都等同於value,而且[i,j)是[first,last)之中符合此一性質的最大子區間

bool binary_search (forwarditerator first, forwarditerator last, const t& value)

bool binary_search (forwarditerator first, forwarditerator last, const t& value, compare comp)

// 查詢是否在[first,last)中存在iterator i,滿足 !(*i

// 存在則返回true,否則返回false. 

注:如果查詢的是自定義型別,則需在定義型別的時候,過載'<'或者'>'運算子,使元素有序,或者在結構體外定義比較友元函式,在查詢的時候,stl查詢函式會自動呼叫比較函式,比較的時候只是根據定義的比較函式進行比較,如果比較函式中,只使用了結構體元素的一部分,則比較是也只是進行部分匹配,不會是結構體的完全匹配,如果要完全匹配只能是在比較函式中使用上結構體中的所有元素。

例:

#include #include #include #include using namespace std;

typedef struct cinvnode

STL中的二分查詢

本文 於 使用的時候注意 必須用在非遞減的區間中 二分查詢的原理非常簡單,但寫出的 中很容易含有很多bug,二分查詢一文中講解過如何實現不同型別的二分查詢,但是否一定要自己去實現二分查詢呢?答案顯然是否定的,本文將講解stl中與二分查詢有關函式的具體使用方法及其實現原理。stl中與二分查詢相關的函式...

stl 二分查詢

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

STL 二分查詢

實現原始碼 1.在乙個遞增的陣列 或vector 中查詢元素屬於 s e 的下標 2.查詢遞增陣列中元素是否存在 使用binary search 注 對於結構體,要麼過載小於符號 bool operator 要麼定義有小於符號含義的cmp函式。3.應用在遞減序列中 include include i...