C++ STL:lower_bound實現

來源:互聯網
上載者:User

標籤:

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實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.