1. 程式人生 > 其它 >C++ 二分查詢函式 lower_bound upper_bound

C++ 二分查詢函式 lower_bound upper_bound

C++ 二分查詢函式 lower_bound upper_bound

包含在標頭檔案algorithm中。
lower_bound

  (ForwardIterator first, ForwardIterator last,const T& val)

  (ForwardIterator first, ForwardIterator last,const T& val, Compare cmp)

  返回一個 指向 [first,last) 中第一個大於等於 數val的 iterator。

upper_bound

  (ForwardIterator first, ForwardIterator last,const T& val)

  (ForwardIterator first, ForwardIterator last,const T& val, Compare cmp)

  返回一個 指向 [first,last) 中第一個大於 數val的 iterator。

用法示例:

#include <iostream>
#include <algorithm>
using namespace std;
int a[100];
int d[100];
const int INF = 0x3f3f3f3f;
int main(){
    int n;
    int num[] = {1,5,2,6,8,1,2,5};
    sort(num,num+sizeof(num)/sizeof(int));// 1 1 2 2 5 5 6 8
    int pos1 = lower_bound(num,num+8,8) - num;//返回陣列中第一個大於或等於被查數的下標位置 
    int pos2 = upper_bound(num,num+8,8) - num;//返回陣列中第一個大於被查數的下標位置 
    cout << pos1 << " " << pos2 << endl;
    sort(num,num+sizeof(num)/sizeof(int),greater<int>());//8 6 5 5 2 2 1 1
    //如果從小到大排序,除非查詢不到返回8,否則都返回0,沒有意義。 
    pos1 = lower_bound(num,num+8,-1,greater<int>()) - num;//返回陣列中第一個小於或等於被查數的下標位置 
    pos2 = upper_bound(num,num+8,8,greater<int>()) - num;//返回陣列中第一個小於被查數的下標位置 
    cout << pos1 << " " << pos2 << endl;
    return 0;
}