lower_bound 函数在二分中的应用

​【lower_bound 函数简介】
● lower_bound 是 C++ STL 中二分查找的核心函数,定义在<algorithm>头文件中,专门用于有序序列的二分查找,返回第一个大于等于目标值的元素迭代器,是实现高效二分查找的便捷工具,无需手动编写二分循环,大幅降低代码复杂度。
● lower_bound 的时间复杂度为 O(log n),其中 n 为待查有序序列的元素个数。
● lower_bound 仅支持随机访问迭代器(vector/array/deque),list 需转存为 vector 后使用。
● 在 C++ 中,静态数组(如 int arr[N]; 形式的固定长度数组)完全可以直接使用 lower_bound 函数实现二分查找,核心要点是保证数组有序,并通过“数组首地址 + 尾地址偏移”的方式传递查找范围,用法与 vector 高度一致,仅在范围传参和下标计算上有细微区别。

// 查找升序数组中第一个 >= target 的元素
lower_bound(arr, arr + n, target); 

// 查找降序数组中第一个 <= target 的元素
lower_bound(arr, arr + n, target, greater<int>());

【算法代码一:vector存数据】

#include <bits/stdc++.h>
using namespace std;

vector<int> v;
int n,x,val;

int main() {
    cin>>n;
    while(n--) {
        cin>>x;
        v.push_back(x);
    }

    cin>>val;
    auto it=lower_bound(v.begin(),v.end(),val);
    if(it!=v.end()) {
        cout<<"Found at index:"<<it-v.begin();
    } else cout<<"Not found";

    return 0;
}

/*
in:
5
1 3 7 12 61
11

out:
Found at index:3
*/

【算法代码二:静态数组存数据】

#include <bits/stdc++.h>
using namespace std;

const int maxn=1e3+5;
int a[maxn];
int n,val;

int main() {
    cin>>n;
    for(int i=0; i<n; i++) {
        cin>>a[i];
    }

    cin>>val;
    auto it=lower_bound(a,a+n,val);
    if(it!=a+n) {
        cout<<"Found at index: "<<it-a;
    } else cout<<"Not found";

    return 0;
}

/*
in:
5
1 3 7 12 61
11

out:
Found at index: 3
*/




【参考文献】
https://www.bilibili.com/video/BV1juLBzREHp/
https://www.bilibili.com/video/BV1mt4y1u7Zg/
https://www.bilibili.com/video/BV1zhR5YnEjc/
https://c.biancheng.net/view/i0ur5s4.html

 

​

posted @ 2026-02-10 21:12  Triwa  阅读(101)  评论(0)    收藏  举报