lower_bound( )与upper_bound( )学习
学习 Bound Lower upper
2023-09-14 09:11:22 时间
转自:https://blog.csdn.net/qq_40160605/article/details/80150252,这个讲的非常全面!
1.从小到大排序的数组
lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
#include <iostream> #include<vector> #include<algorithm> int main(){ int num[6]={1,2,4,7,15,34}; sort(num,num+6); //按从小到大排序 int pos1=lower_bound(num,num+6,7)-num; //返回数组中第一个大于或等于被查数的值 int pos2=upper_bound(num,num+6,7)-num; cout<<pos1<<" "<<pos2<<endl; vector<int> num2={0,1,2,3,6};//也可以在vector中 sort(num2.begin(),num2.end()); int p1=lower_bound(num2.begin(),num2.end(),6)-num2.begin(); int p2=upper_bound(num2.begin(),num2.end(),6)-num2.begin(); cout<<p1<<" "<<p2<<endl; return 0; } //3 4 4 5
2.从大到小排序的数组
重载lower_bound()和upper_bound():
lower_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
int cmd(int a,int b){ return a>b; } int main(){ int num[6]={1,2,4,7,15,34}; sort(num,num+6,cmd); //按从大到小排序 int p1=lower_bound(num,num+6,7,greater<int>())-num;//小于等于 int p2=upper_bound(num,num+6,7,greater<int>())-num;//小于 cout<<p1<<" "<<p2; return 0; } //2 3
相关文章
- C语言学习——数组
- 从零学习Jenkins部署SpringBoot项目
- es7学习笔记 cpu负载不均衡、超长fullGC、大量400报错[通俗易懂]
- Excel VBA学习自定义函数-从表1查找字符复制到表2
- Cobaltstrike 学习笔记(三)CS与MSF联动
- Java中注解学习系列教程-6 excel导出优化plush版
- MySQL数据库原理学习(二十四)
- 论文推荐:基于深度对抗学习的超声图像乳腺肿瘤分割与分类
- Rust学习笔记 常用trait 类型转换,操作符相关
- odoo ORM API学习总结兼orm学习教程
- 实践在西安,学习linux的精彩(西安linux实习)
- 2020A2M人工智能与机器学习创新峰会即将于上海召开!
- 学习 Linux,一起聊聊大话 Linux!(大话linux)
- 深入学习Redis配置文件探究(看redis的配置文件)
- W3C教程中学习Redis(w3c教程中的redis)
- C#中的正则表达式学习资料
- JavaScript基本概念初级讲解论坛贴的学习记录
- MySQL触发器学习总结
- 正则表达式学习问答