STL里面的函數(不定期更新)

upper_bound, lower_bound

這兩個函數類似,以upper_bound為例,該函數有兩種形式:

template <class ForwardIterator, class T>
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val)

template <class ForwardIterator, class T, class Compare>
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);

函數接受兩個迭代器 first, last,一個值 val。函數所做的工作如下:以 val 作為上界,在first, last 中尋找一個區間,這個區間的上界就是 val, 顯然,這樣的區間有很多個,我們要選一個最貼近上界的區間。返回的迭代器就指向這個區間的右邊的第一個值。

所謂的大于,小于可以自己定義。lower_bound() 返回以 val 為下界的區間的左端點的迭代器。

  • upper_bound 示例:
int main() {
    int input[] = {1,2,2,3,4,4,5,6,7,8,10,45};
    vector<int> v(input, input+12);
    vector<int>::iterator it1 , it2;

    // points to eight element in v, index from 0 to 11, *it1 = 7
    it1 = upper_bound(v.begin(), v.end(), 6); 
    cout << it1 - v.begin() << endl;

    // points to six element in v, *it2 = 5
    it2 = upper_bound(v.begin(), v.end(), 4);
    cout << it2 - v.begin() << endl;

    return 0;
}
  • lower_bound示例:
int main() {
    int input[] = {1,2,2,3,4,4,5,6,7,8,10,45};
    vector<int> v(input, input+12);
    vector<int>::iterator it1 , it2;

    // points to eight element in v, *it1 = 4 
    it1 = lower_bound(v.begin(), v.end(), 4); 
    cout << *it1 << endl;
    cout << it1 - v.begin() << endl;

    // points to six element in v, *it2 = 10
    it2 = lower_bound(v.begin(), v.end(), 10);
    cout << *it2 << endl;
    cout << it2 - v.begin() << endl;

    return 0;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容