lower_bound()返回值

来源:互联网 发布:qq.com 域名 编辑:程序博客网 时间:2024/05/29 10:03

lower_bound()函数实现功能就是二分查找,函数lower_bound()在firstlast中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置。
举例说明:
例如有数组a[]={1,2,3,4,5,6,7,10},lower_bound(a,a+5,4)-a的返回值就是3(需要注意的是这里必须减去a),返回值3也就是数组中4的下标;那么lower_bound(a,a+8,15)-a的返回值应该是什么?是8,这是因为如果所有元素都小于val,则返回last的位置
测试代码:

#include<iostream>#include<algorithm>using namespace std;int main(){    int a[]={1,2,3,4,5,6,10,11,12,13};    cout<<lower_bound(a+5,a+10,13)-a<<endl;    cout<<lower_bound(a,a+10,5)-a<<endl;    cout<<lower_bound(a,a+10,20)-a<<endl;    return 0;} 

如有不当之处欢迎指出!!

0 0
原创粉丝点击