可以按是否需要排序區間分為兩組:
a. count,find
b. binary_search,lower_bound,upper_bound,equal_range
a組不需排序區間, b組需要排序區間。
當乙個區間被排序,優先選擇b組,因為他們提供對數時間的效率。而a則是線性時間。
另外a組b組所依賴的查詢判斷法則不同,a使用相等性法則(查詢物件需要定義operator==), b使用等價性法則(查詢物件需要定義operator
如果在c++ stl容器中包含了有序的序列,stl提供了四個函式進行搜尋,他們是利用二分查詢實現的(binary search).其中:假定相同值的元素可能有多個
lower_bound 返回第乙個符合條件的元素位置
upper_bound 返回最後乙個符合條件的元素位置
equal_range 返回所有等於指定值的頭/尾元素的位置,其實就是lower_bound和upper_bound
binary_search 返回是否有需要查詢的元素。
#(1)stl中關於二分查詢的函式有三個:lower_bound 、upper_bound 、binary_search —— 這三個函式都運用於有序區間(當然這也是運用二分查詢的前提),下面記錄一下這兩個函式;(2)forwarditer lower_bound(forwarditer first, forwarditer last,const _tp& val)演算法返回乙個非遞減序列[first, last)中的第乙個大於等於值val的位置;include
#include
#include
using namespace std;
int main ()
(3)forwarditer upper_bound(forwarditer first, forwarditer last, const _tp& val)演算法返回乙個非遞減序列[first, last)中的第乙個大於值val的位置。
二:lower_bound和upper_bound如下圖所示:
你想知道的
在無序區間
在有序區間
在set或map上
在multiset或multimap上
期望值是否存在?
find
binary_search
count
find
期望值是否存在?如果有,第乙個等於這個值的物件在**?
find
equal_range
find
find或lower_bound(參見下面)
第乙個不在期望值之前的物件在**?
find_if
lower_bound
lower_bound
lower_bound
第乙個在期望值之後的物件在**?
find_if
upper_bound
upper_bound
upper_bound
有多少物件等於期望值?
count
equal_range,然後distance
count
count
等於期望值的所有物件在**?
find(迭代)
equal_range
equal_range
equal_range
STL 常用演算法(二)查詢演算法
演算法簡介 1 find 功能描述 函式原型 include include include void test01 查詢容器中是否有 5 這個元素 vector int iterator it find v.begin v.end 5 if it v.end else class person 過...
STL中的查詢演算法
stl中有很多演算法,這些演算法可以用到乙個或多個stl容器 因為stl的乙個設計思想是將演算法和容器進行分離 也可以用到非容器序列比如陣列中。眾多演算法中,查詢演算法是應用最為普遍的一類。單個元素查詢 1 find 比較條件為元素是否相等的查詢 template inputiterator fin...
STL 非變異演算法之查詢
本博文主要講了find find if find first of find end adjacent find search search n 這些stl中的查詢演算法 例項1 include include include using namespace std bool myless int ...