lower_bounder()和upper_bound()的函数

lower_bound() 、upper_bound()都运用于有序区间的二分查找。

ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置。

ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)算法返回一个非递减序列[first, last)中的第一个大于值val的位置。

lower_bound和upper_bound如下图所示:

  不过除此之外,这两个函数还分别有一个重载函数,可以接受第四个参数。如果第四个参数传入greater<Type>(),其中Type改成对应类型,那么upper_bound则返回指向被查值<查找值的最小指针,lower_bound则返回指向被查值<=查找值的最小指针。
  最后说一点使用的注意事项,先看这么一句话“ The elements in the range shall already be sorted according to this same criterion (operator< or comp), or at least partitioned with respect to val”(引用自http://www.cplusplus.com/reference/algorithm/upper_bound/)。简单来说,如果你用上述两个函数三个参数的那种形式,记得那个左闭右开的区间要为非递减的顺序,如果你给第四个参数传入greater<Type>(),则区间为非递增的顺序。

 1 #include <iostream>
 2 #include <algorithm>
 3 
 4 using namespace std;
 5 
 6 int seq1[] = {1, 2, 3, 3, 4, 5}, seq2[] = {9, 8, 7, 7, 6, 5};
 7 //注释掉的是错误用法
 8 int main()
 9 {
10     //cout<<upper_bound(seq1, seq1+6, 3, greater<int>()) - seq1<<endl;
11     //cout<<lower_bound(seq1, seq1+6, 3, greater<int>()) - seq1<<endl;
12     cout<<upper_bound(seq1, seq1+6, 3) - seq1<<endl;
13     cout<<lower_bound(seq1, seq1+6, 3) - seq1<<endl;
14 
15     cout<<endl;
16 
17     cout<<upper_bound(seq2, seq2+6, 7, greater<int>()) - seq2<<endl;
18     cout<<lower_bound(seq2, seq2+6, 7, greater<int>()) - seq2<<endl;
19     //cout<<upper_bound(seq2, seq2+6, 7) - seq2<<endl;
20     //cout<<lower_bound(seq2, seq2+6, 7) - seq2<<endl;
21     return 0;
22 }

 内容来源:【1】http://blog.csdn.net/u011008379/article/details/50725670

      【2】http://blog.csdn.net/u013475704/article/details/46458723

感谢以上博主。

原文地址:https://www.cnblogs.com/zxhyxiao/p/7819785.html