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>(),则区间为非递增的顺序。

 #include <iostream>
#include <algorithm> using namespace std; int seq1[] = {, , , , , }, seq2[] = {, , , , , };
//注释掉的是错误用法
int main()
{
//cout<<upper_bound(seq1, seq1+6, 3, greater<int>()) - seq1<<endl;
//cout<<lower_bound(seq1, seq1+6, 3, greater<int>()) - seq1<<endl;
cout<<upper_bound(seq1, seq1+, ) - seq1<<endl;
cout<<lower_bound(seq1, seq1+, ) - seq1<<endl; cout<<endl; cout<<upper_bound(seq2, seq2+, , greater<int>()) - seq2<<endl;
cout<<lower_bound(seq2, seq2+, , greater<int>()) - seq2<<endl;
//cout<<upper_bound(seq2, seq2+6, 7) - seq2<<endl;
//cout<<lower_bound(seq2, seq2+6, 7) - seq2<<endl;
return ;
}

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

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

感谢以上博主。

最新文章

  1. [.net 面向对象程序设计进阶] (20) 反射(Reflection)(上)利用反射技术实现动态编程
  2. Effective Modern C++ 42 Specific Ways to Improve Your Use of C++11 and C++14
  3. Android 四大组件之Service
  4. Android接收短信
  5. 多线程下HashMap的死循环问题
  6. windows访问linux共享
  7. Android 动画及属性动画
  8. C# List 扩展排序
  9. 本地存储 web storage
  10. Linux查看监听端口的脚本测试
  11. IaaS,PaaS和SaaS
  12. linux 内核 内存管理 slub算法 (一) 原理
  13. 让运行着的ASP.NET Web程序重新启动
  14. jwt-auth错误小结
  15. C语言复习---打印菱形
  16. oracle 嵌套查询
  17. 简明PR教程
  18. 干货!Jenkins下配置findbugs、pmd及checkstyle实现代码自动检测
  19. CecOS Virtualization
  20. 百万数据测试 Entity Framework 到底有多慢

热门文章

  1. Dom4j官网解释实例
  2. npm 安装删除模块
  3. Leetcode147. Insertion Sort List对链表进行插入排序
  4. Redis源码解析:15Resis主从复制之从节点流程
  5. win7旗舰版64位搭建FTP服务器
  6. js移动端判断上下左右划屏
  7. iview中table的render()函数
  8. Leetcode12.Integer to Roman整数转罗马数字
  9. Javascript-正则表达式常用验证
  10. SQL竖表转横表Json数据