std::binary_search和std::lower_bound的关系,哪些不同,以及要注意的点

文章讲述了C++标准库中的std::binary_search函数与std::lower_bound的区别,前者仅用于精确查找并返回值是否存在,而后者返回第一个不满足条件的值的位置。两者结合使用时,通过判断两个条件确认目标值。
摘要由CSDN通过智能技术生成

1、std::binary_search内部用std::lower_bound来进行查询。

2、std::binary_search只在精确查到指定的值的时候才返回true,而std::lower_bound不是

3、std::binary_search只给出是不是存在这个值,但不告诉你这个值的位置。而std::lower_bound会返回位置,但不一定是这个值,lower_bound是根据查询规则来返回位置

std::lower_bound查询到的只是第一个不满足查询条件的那个值,但和你要查的那个值不一定相等,所以binary_search在最后又用!_Pred(_Val, *_UFirst)进行反向判断。

一句就是:

bool b0=!(a<b);

bool b1=!(b<a);

if(b0 && b1){ printf("a==b"); }

简述就是:如果a不小于b,并且b又不小于a,那么a和b相等。

反映到binary_search上就是,!_Pred(*_UFirst, _Val) 和!_Pred(_Val, *_UFirst)均为true,那么就是要找的那个值了。

因为std::lower_bound里,满足查询结果的就是第一个!_Pred(*_UFirst, _Val) 为true的,所以再检查一下!_Pred(_Val, *_UFirst)就行了。


		// FUNCTION TEMPLATE binary_search
template<class _FwdIt,
	class _Ty,
	class _Pr>
	_NODISCARD inline bool binary_search(_FwdIt _First, _FwdIt _Last, const _Ty& _Val, _Pr _Pred)
	{	// test if _Val equivalent to some element, using _Pred
	_Adl_verify_range(_First, _Last);
	auto _UFirst = _Get_unwrapped(_First);
	const auto _ULast = _Get_unwrapped(_Last);
	_UFirst = _STD lower_bound(_UFirst, _ULast, _Val, _Pass_fn(_Pred));
	return (_UFirst != _ULast && !_Pred(_Val, *_UFirst));
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值