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;
}

---------------------------------------------------------------------------------------------------------------------------------

除此之外的一些小知识

 å¨è¿éæå¥å¾çæè¿°

  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值