手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

如何使用C++的lower/upper_bound

时间:2024-10-13 05:36:44

1、lower_bound 可以在一个区间中二分查找,返回指向第一个大于等于 x 的元素位置的指针(或迭代器)不过,这个区间必须是有序的,即提前从小到大排过序,通常使用时会先sort一下lower_bound(首指针,尾指针,x);和所有 "algorithm" 的函数一样,这个函数接受的区间左闭右开,也要在头文件中加上 "#include<algorithm>"如图,因为 lower_bound 返回参数为指针,所以要用 "*" 解除应用

如何使用C++的lower/upper_bound
如何使用C++的lower/upper_bound

2、lower_bound 也可以接受迭代器,例如 STL vector 中的 begin()/end()vector 也是左闭右开,写起来十分方便

如何使用C++的lower/upper_bound

3、当然,我们可以手写二分代替lower_bound,代码也不是很长该代码来源于网络

如何使用C++的lower/upper_bound
如何使用C++的lower/upper_bound

4、upper_bound 的使用方法和 lower_bound 差不多(毕竟它们名字就很像)upper_bound 返回第一个大于 x 的元素的指针(或迭代器)

如何使用C++的lower/upper_bound

5、这个是 upper_bound 的迭代器版本

如何使用C++的lower/upper_bound

6、和 lower_bound 一样,upper_bound 手写起来也并不是很难代码来源于网络

如何使用C++的lower/upper_bound

7、通过指针(或迭代器)的加减我们还可以求出返回元素的下标

如何使用C++的lower/upper_bound
如何使用C++的lower/upper_bound

8、以上就是 lower_bound/upper_bound 的主要使用方法及作用这两个函数都可以手写,但如果想要节省时间,就直接调用吧

© 手抄报圈