upper_bound和lower_bound的使用 详解

 前提:有序

1.从小到大

lower_bound(start,last,n)  :返回第一个大于等于n的地址

upper_bound(start,last,n)  :返回第一个大于n的地址

 

2.从大到小

lower_bound(start,last,n,greater<int>())  :返回第一个小于等于n的地址

upper_bound(start,last,n,greater<int>())  :返回第一个小于n的地址

 

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int cmp(int a,int b)
{
	return a>b;
}
int main()
{
	int a[10]={12,0,3,6,999,45,1,864,75,26};
	sort(a,a+10);
	for(int i=0;i<10;i++)
	{
		cout<<a[i]<<" ";
	}
	cout<<endl;
	cout<<"33在:"<<lower_bound(a,a+10,33)-a<<endl;
	cout<<"6在"<<upper_bound(a,a+10,6)-a<<endl;

	sort(a,a+10,cmp);
	cout<<"从大到小排列"<<endl; 
	for(int i=0;i<10;i++)
	{
		cout<<a[i]<<" ";
	}
	cout<<endl;
	
	cout<<"33在:"<<lower_bound(a,a+10,33,greater<int>())-a<<endl;
	cout<<"6在"<<upper_bound(a,a+10,6,greater<int>())-a<<endl;
	
	
	
	return 0;
}

 

 

  • 7
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值