標籤:
lower_bound(begin, end, target)用來尋找一個已排序的序列中[begin, end)第一個大於等於target的元素。數組A如下:
value: 1, 2, 2, 3, 4, 5, 5, 6, 7
index: 0, 1, 2, 3, 4, 5, 6, 7, 8
這樣的一個序列,如果尋找5的lower_bound,返回的應該是第一個5即A[5]。下面是摘自cplusplus.com上的lower_bound代碼
template <class ForwardIterator, class T> ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val){ ForwardIterator it; iterator_traits<ForwardIterator>::difference_type count, step; count = distance(first,last); while (count>0) { it = first; step=count/2; advance (it,step); if (*it < val) { // or: if (comp(*it,val)), for version (2) first = ++it; count -= step+1; } else count = step; } return first;}
如果搜尋對象只是數組的話還可以再簡化一點:
count = last - start;while (count > 0) { step = count/2; int* it = first + step; if (*it < target) { count = count - (step + 1); first = it + 1; } else { count=step; }}return first;
基本情況: 當輸入只有一個元素時,而該元素不是要尋找的元素時返回end,即該元素的後一個位置
當在中的數組中找4的lower_bound時,第一次*it取到的值是4,因為這不是簡單的二分搜尋,而是要返回第一大於等於尋找元素的位置,所以搜尋不能在此時結束。但是可以確定5~7這一部分可以不用搜尋了,因為當前至少有一個元素即*it是大於等於4了,因而縮小尋找範圍(count=step)。這個尋找範圍並不包括已找到的4,為什麼是這樣?分情況討論:
1. 當前面的這個範圍沒有合格數時,就會將範圍最後的位置的後一位置返回,而此位置正好是4所在的位置,即(*it>= target時it所在的位置,它是符合尋找條件的)。
2. 當前面的這個方位含有合格數時,此時當前的這個4就不是lower_bound,也就不用考慮了
C++ STL:lower_bound實現