C++STL容器(lower_bound,upper_bound)

时间:2023-03-09 17:49:35
C++STL容器(lower_bound,upper_bound)

C++STL容器中有三种二分查找函数,这里分享其中的两个

这两个函数其实都可以理解为不破坏数组次序的前期下能将目标元素插入到数组的第几个位置,不过在细节上两个函数有所差异

int d[6]={0,2,4,6,8,10},x=1,y=2;

int pos1=lower_bound(d,d+6,x)-d;

int pos2=lower_bound(d,d+6,y)-d;

lower_bound返回值:pos1=1; pos2=1;

int pos1=upper_bound(d,d+6,x)-d;

int pos2=upper_bound(d,d+6,y)-d;

upper_bound返回值:pos1=1; pos2=2;