【C++基礎編程】#028 lower_bound()和upper_bound()函數簡介

簡介

lower_bound(int* first,int* last,val);
C++ STL庫 lower_bound() 函數在first和last中的前閉後開區間,進行二分查找。返回從first開始的第一個大於或等於val的元素的地址。如果所有元素都小於val,則返回last的地址。注意:數組必須是排好序的數組。

與之對應:
upper_bound(int* first,int* last,val);
C++ STL庫 upper_bound() 函數在first和last中的前閉後開區間,進行二分查找。返回從first開始的第一個大於val的元素的地址。如果所有元素都小於val,則返回last的地址。注意:數組必須是排好序的數組。

注:
需引入頭文件:
#include<algorithm>

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;
}

upper_bound()函數官方定義

template <class ForwardIterator, class T>
  ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val)
{
  ForwardIterator it;
  iterator_traits<ForwardIterator>::difference_type count, step;
  count = std::distance(first,last);
  while (count>0)
  {
    it = first; step=count/2; std::advance (it,step);
    if (!(val<*it))                 // or: if (!comp(val,*it)), for version (2)
      { first=++it; count-=step+1;  }
    else count=step;
  }
  return first;
}

舉例說明

#include <iostream>     // std::cout
#include <algorithm>    // std::lower_bound, std::upper_bound, std::sort
#include <vector>       // std::vector

int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  std::vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20

  std::sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30

  std::vector<int>::iterator low,up;
  low=std::lower_bound (v.begin(), v.end(), 20); 
  up= std::upper_bound (v.begin(), v.end(), 20); 

  std::cout << "lower_bound at position " << (low - v.begin()) << '\n'; //輸出:3
  std::cout << "upper_bound at position " << (up - v.begin()) << '\n';	//輸出:6

  return 0;
}

參考資料

http://www.cplusplus.com/reference/algorithm/lower_bound/
http://www.cplusplus.com/reference/algorithm/upper_bound/
https://blog.csdn.net/qq_38786209/article/details/78470260

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章