c++小知识点:upper_bound
2022/2/6 17:15:47
本文主要是介绍c++小知识点:upper_bound,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
第一种情况
头文件:#include<algorithm>
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序的数组中进行查找的。
举例说明:
第一种用法
对于STL库中的容器vector,可以结合内嵌的迭代器iterator来使用upper_bound 函数。
vector<int> v={0 ,2 ,1 ,4 ,7 ,6}; vector<int>::iterator up1; up1=upper_bound(v.begin(),v.end(),3); cout<<up1-v.begin()<<endl;
第二种用法
对于数组又改如何操作呢?
类似的,我们可以写下如下程序:
int a[6]={1,3,5,6,7,9}; int temp=upper_bound(a,a+6,7)-a; cout<<temp<<endl;
类似:
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<<" "<<num[pos1]<<endl; cout<<pos2<<" "<<num[pos2]<<endl; sort(num,num+6,cmd); //按从大到小排序
--------------------------------------------------------------------------------------第二种情况
其实也是第一种情况的部分,只不过换了一种形式
当set里所有值都小于关键字时,lower_bound返回a.end()
以std::map为例,
lower_bounder()返回的迭代器指向第一个[大于等于]目标值的元素(以升序为例),
upper_bound()返回的迭代器指向第一个 [大于]目标值的元素(以升序为例)。
#include <iostream> #include <map> int main() { std::map<char, int> mymap; std::map<char, int>::iterator itlow, itup; mymap['a'] = 20; mymap['b'] = 40; mymap['c'] = 60; mymap['d'] = 80; mymap['e'] = 100; itlow = mymap.lower_bound('b'); // itlow points to b itup = mymap.upper_bound('d'); // itup points to e (not d!) mymap.erase(itlow, itup); // erases [itlow,itup) // print content: for (std::map<char, int>::iterator it = mymap.begin(); it != mymap.end(); ++it) std::cout << it->first << " => " << it->second << '\n'; return 0; }
---------------------------------------------------------------------------------------------------------------------------------
除此之外的一些小知识
这篇关于c++小知识点:upper_bound的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-03微信支付提示下单账户与支付账户不一致-icode9专业技术文章分享
- 2024-07-03微信支付提示订单号重复-icode9专业技术文章分享
- 2024-07-02微服务启动nacos注册上去了,但是一直没有收到请求-icode9专业技术文章分享
- 2024-07-02如何检查文件的编码格式-icode9专业技术文章分享
- 2024-07-02sublime 更改编码格式-icode9专业技术文章分享
- 2024-06-30uniAPP 实现全屏左右滚动滚动的效果-icode9专业技术文章分享
- 2024-06-30如何在本地使用授权或插件-icode9专业技术文章分享
- 2024-06-30伪静态规则配置方法汇总-icode9专业技术文章分享
- 2024-06-29易优CMS安装常见问题汇总-icode9专业技术文章分享
- 2024-06-28易优新手必读安装教程-icode9专业技术文章分享