lower_bound和upper_bound的区别

这篇博客详细介绍了C++中使用二分查找算法实现lower_bound和upper_bound函数的过程,并展示了如何在有序数组和向量中查找指定元素的边界。通过示例代码解释了这两个函数在正序和逆序排列中的不同行为,并提供了测试用例进行验证。同时,文中还提及了二分查找与开方查找的对比。
摘要由CSDN通过智能技术生成

正序(从小到大)

lower_bound()是返回第一个大于等于 i 值的元素的地址
upper_bound()是返回第一个大于 i 值的元素的地址

逆序(从大到小)

lower_bound()是返回第一个小于等于 i 值的元素的地址
upper_bound()是返回第一个小于 i 值的元素的地址

头文件:

#include<algorithm>

自己写这个函数的代码(二分查找)

int upper_bound(int l,int r,int x)
{  while(l<r){
	int mid=(l+r)/2;
	if(a[mid]>x)r=mid;
	else l=mid+1;
}
return l;
}
int lower_bound(int l,int r,int x)
{  while(l<r){
	int mid=(l+r)/2;
	if(a[mid]>=x)r=mid;
	else l=mid+1;
}
return l;
}

对比二分查找

int binarysearch(int l,int r,int x)
{  while(l<=r){
	int mid=(l+r)/2;
	if(a[mid]==x)return mid;
	else if(a[mid]>x)r=mid-1;
	else l=mid+1;
}
return -1;
}

对比开方

double sqrt(double x)
{  double l=1,r=x,mid;
    while(r-l>eps){	//精度 相当于 r>l
	    mid=(l+r)/2;
	    if(mid*mid>x)r=mid;
		else l=mid;
 
}
return mid;
}

vector和数组都适用

看一看这个代码就什么都懂啦!

(~ ̄▽ ̄)~

#include<iostream>
#include<algorithm>
#include<vector>
#include<iterator>
using namespace std;
bool cmp(int a, int b)
{
	return a>b;
}
int main()
{
	vector<int> v;
	v.push_back(1);
	v.push_back(3);
	v.push_back(19);
	v.push_back(2);
	v.push_back(4);
	v.push_back(7);
	sort(v.begin(),v.end());
	for(auto it:v) 
	{
		cout<<it<<' ';
	}
	printf("\n");
	vector<int>::iterator it; 
	it = lower_bound(v.begin(),v.end(),4);
	cout<<"lower bound: "<<*it<<endl;
	cout<<"lower bound position: "<<lower_bound(v.begin(),v.end(),4)-v.begin() + 1<<endl;
	
	it = upper_bound(v.begin(),v.end(),4);
	cout<<"upper bound: "<<*it<<endl;
	cout<<"upper bound position: "<<upper_bound(v.begin(),v.end(),4)-v.begin() + 1<<endl;
	
	cout<<"——逆序——"<<endl;
	sort(v.begin(),v.end(), cmp);
	for(auto it:v) 
	{
		cout<<it<<' ';
	}
	printf("\n");
	
	it = lower_bound(v.begin(),v.end(),4, cmp);
	cout<<"lower bound: "<<*it<<endl;
	cout<<"lower bound position: "<<lower_bound(v.begin(),v.end(),4, cmp)-v.begin() + 1<<endl;
	
	it = upper_bound(v.begin(),v.end(),4, cmp);
	cout<<"upper bound: "<<*it<<endl;
	cout<<"upper bound position: "<<upper_bound(v.begin(),v.end(),4, cmp)-v.begin() + 1<<endl;
	return 0;
}

运行结果截图:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值