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