upper_bound和lower_bound用法
来源:互联网 发布:mysql update 阻塞 编辑:程序博客网 时间:2024/05/22 15:45
两个函数的用法类似,在一个左闭右开的有序区间里进行二分查找,需要查找的值由第三个参数给出。
对于upper_bound来说,返回的是被查序列中第一个大于查找值的指针,也就是返回指向被查值>查找值的最小指针,lower_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[] = {1, 2, 3, 3, 4, 5}, seq2[] = {9, 8, 7, 7, 6, 5};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+6, 3) - seq1<<endl; cout<<lower_bound(seq1, seq1+6, 3) - seq1<<endl; cout<<endl; cout<<upper_bound(seq2, seq2+6, 7, greater<int>()) - seq2<<endl; cout<<lower_bound(seq2, seq2+6, 7, greater<int>()) - seq2<<endl; //cout<<upper_bound(seq2, seq2+6, 7) - seq2<<endl; //cout<<lower_bound(seq2, seq2+6, 7) - seq2<<endl; return 0;}
0 0
- upper_bound和lower_bound用法
- upper_bound和lower_bound用法
- upper_bound和lower_bound的用法
- lower_bound和upper_bound的用法
- upper_bound和lower_bound的用法
- STL 二分查找 upper_bound和lower_bound用法
- upper_bound\lower_bound的用法
- lower_bound()&&upper_bound()得用法
- lower_bound,upper_bound的用法
- 关于upper_bound,和lower_bound
- stl lower_bound 和 upper_bound
- lower_bound和upper_bound
- lower_bound()和upper_bound()
- lower_bound()和upper_bound
- STL lower_bound和upper_bound
- [STL] lower_bound和upper_bound
- lower_bound和upper_bound
- 关于lower_bound 和upper_bound
- 【Android】安卓学习笔记之用内容提供器访问其他程序中的数据
- HDU1095 A+B for Input-Output Practice (VII)(入门水题,C,Java两个版本)
- java的动态代理机制
- Xcode基本使用
- 所有的文章全部用新的编辑器重新编辑
- upper_bound和lower_bound用法
- 【template】练习
- 2016寒假训练——搜索
- redis安装
- CocoaPods安装指南
- Spring-02-详细配置
- android shape绘制组件边框
- Eclipse 搭建Spring Struts2
- 程序员如何留住健康?