STL 二分法 upper_bound()与lower_bound()使用方法
来源:互联网 发布:excel怎么合并数据 编辑:程序博客网 时间:2024/05/18 13:41
lower_bound( first, last,val)算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置
的迭代器
。
upper_bound(first, last, val)算法返回一个非递减序列[first, last)中第一个大于val的位置的迭代器。
使用头文件
#include<iostream>
using namespace std;
测试样例
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[]={0,1,2,4,5,6,7,8,9,10}; //返回对应元素 cout<<*upper_bound(a,a+10,3)<<endl; //4 第一个大于 cout<<*lower_bound(a,a+10,3)<<endl; //4 第一个大于等于 //返回对应下标 cout<<upper_bound(a,a+10,4)-a<<endl; //4 第一个大于 cout<<lower_bound(a,a+10,4)-a<<endl; //3 第一个大于等于 cout<<upper_bound(a,a+10,-1)-a<<endl; //0 未找到将返回第一个 cout<<lower_bound(a,a+10,-1)-a<<endl; //0 未找到将返回第一个 cout<<upper_bound(a,a+10,11)-a<<endl; //10 未找到将返回最后 cout<<lower_bound(a,a+10,11)-a<<endl; //10 未找到将返回最后 /* 注意: 两个函数使用时,必须确定序列为非递减序列,否则会发生错误 */ return 0;}
这两个函数还分别有一个重载函数,可以接受第四个参数。如果第四个参数传入greater<Type>(),其中Type改成对应类型,可以用于查找非递增序列
测试样例
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[]={10,9,8,7,6,5,4,2,1,0}; cout<<upper_bound(a,a+10,4,greater<int>())-a<<endl; //7 返回第一个小于 cout<<lower_bound(a,a+10,4,greater<int>())-a<<endl; //6 返回第一个小于等于 cout<<upper_bound(a,a+10,-1,greater<int>())-a<<endl; //10 未找到将返回最后 cout<<lower_bound(a,a+10,-1,greater<int>())-a<<endl; //10 未找到将返回最后 cout<<upper_bound(a,a+10,11,greater<int>())-a<<endl; //0 未找到将返回第一个位置 cout<<lower_bound(a,a+10,11,greater<int>())-a<<endl; //0 未找到将返回第一个位置 return 0;}
两个函数配合使用可以进行查找 有序序列中的元素个数
使用样例
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[]={0,1,2,3,5,5,5,6,7}; //查找元素 5 的个数 cout<<upper_bound(a,a+10,5)-lower_bound(a,a+10,5)<<endl; return 0;}
1 0
- STL 二分法 upper_bound()与lower_bound()使用方法
- STL lower_bound与upper_bound
- upper_bound()与lower_bound()使用方法
- upper_bound() 与 lower_bound() 使用方法
- upper_bound()与lower_bound()使用方法
- upper_bound()与lower_bound()使用方法
- upper_bound()与lower_bound()使用方法
- upper_bound()与lower_bound()使用方法
- Lower_bound与Upper_bound (STL)
- (转)upper_bound()与lower_bound()使用方法
- 【STL】STL之lower_bound与upper_bound
- stl函数之lower_bound 与 upper_bound
- STL中的二分查找,lower_bound();与upper_bound();
- 浅谈STL中的二分lower_bound()与upper_bound()
- stl lower_bound 和 upper_bound
- C++ STL lower_bound upper_bound
- C++ STL lower_bound & upper_bound
- STL lower_bound和upper_bound
- UML九大图
- BLE 广播、扫面、连接相关基础知识
- 剑指offer7——两个栈实现队列
- Visual Studio for Mac 安装&体验
- 二叉树后序线索化以及后序遍历
- STL 二分法 upper_bound()与lower_bound()使用方法
- 关于中值滤波算法,以及C语言实现
- html 表格和表单知识点
- eclipse工作空间配置--------新建菜单初始项
- Windows版本搭建安装React Native环境配置 count not find tools.jar问题
- 《构建之法》 第八章需求分析
- 利用OpenCV和C++实现由RGB图像转化为灰度图,再将灰度图转化为二值图的程序
- Hibernate 实体类 映射文件使用注解方式 经典报错以及解决方法
- Android Studio目录结构