lower_bound( )和upper_bound( )的用法

使用这两个函数都需要包含对应头文件

#include <algorithm>

这两个函数都是采用的二分算法

lower_bound(查找的起始位置,查找的终止为止,需要查找的数 )是返回第一个大于等于需要查找的数的数的地址
比如,要a[]数组中,从[1,n]中第一个大于s的数的下标
pos=lower_bound(a+1,a+n+1,s)-a;
upper_bound(查找的起始位置,查找的终止为止,需要查找的数 )是返回第一个大于需要查找的数的数的地址
注意上面的两种用法都需要原数组是小到大排列的有序数组

可以通过修改比较器,查找第一个小于或小于等于某个数的地址
数组需要从大到小排列
首先需要比较函数
bool cmp(const int &a,const int &b){return a>b;}
比如,要a[]数组中,从[1,n]中第一个小于s的数的下标
pos=lower_bound(a+1,a+n+1,s,cmp)-a;
也可以不写cmp函数,将所有cmp的位置换成greater<i/nt>() 去掉/,int显示不了

这两种函数如果差找不到目标,就返回查找的最后一个元素的地址

代码示例

#include<iostream>
#include<algorithm>
using namespace std;

bool cmp(const int &a,const int &b)
{
	return a>b;
}

int main()
{
	int a[]={1,5,9,11,45,69,101};
	cout<<"数组为 ";
	for(int i=0;i<7;i++)cout<<a[i]<<" ";cout<<endl; 
	int p1=lower_bound(a,a+7,9)-a;
	cout<<"数组中第一个大于等于9的数的下标为 "<<p1<<endl;
	int p2=upper_bound(a,a+7,9)-a;
	cout<<"数组中第一个大于9的数的下标为 "<<p2<<endl;
	sort(a,a+7,cmp);
	cout<<"数组为 ";
	for(int i=0;i<7;i++)cout<<a[i]<<" ";cout<<endl; 
	int p3=lower_bound(a,a+7,9,cmp)-a; 
	cout<<"数组中第一个小于等于9的数的下标为 "<<p3<<endl;
	int p4=upper_bound(a,a+7,9,greater<int>())-a;
	cout<<"数组中第一个小于9的数的下标为 "<<p4<<endl;
}

结果
在这里插入图片描述

  • 29
    点赞
  • 150
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值