1. 引用
#include< algorithm>
2.前提
這個區間必須是有序的,即提前從小到大排過序,通常使用時會先sort一下
3.作用
lower_bound 可以在一個區間中二分查找,返回指向第一個大於等於 x 的元素位置的指針(或迭代器)
upper_bound 可以在一個區間中二分查找,返回指向第一個大於 的元素位置的指針(或迭代器)
lower_bound與upper_bound的區別距離
int a[4]={0,1,2,3};
int k=lower_bound(a,a+4,1)-a; //第一個大於等於 x 的元素位置
此時k的值爲1,因爲數組是從0開始算的,1=1,且位於第二個元素
而 int k=upper_bound(a,a+4,1)-a;//第一個大於 x 的元素位置
此時k的值爲2;
4.使用
lower_bound(首指針,尾指針,x);
但一般使用的時候是求數組下標
lower_bound(首指針,尾指針,x)-首指針;
//數組a,長度爲n,k爲第一個大於等於x的元素位置的下標
int k=lower_bound(a,a+n,x)-a;
//若數組a是不定數組vector<int>a;
int k=lower_bound(a.begin(),a.end(),x)-a.begin();
upper_bound(首指針,尾指針,x);
但一般使用的時候是求數組下標
upper_bound(首指針,尾指針,x)-首指針;
//數組a,長度爲n,k爲第一個大於x的元素位置的下標
int k=upper_bound(a,a+n,x)-a;
//若數組a是不定數組vector<int>a;
int k=upper_bound(a.begin(),a.end(),x)-a.begin();