binary_search、lower_bound、upper_bound

本文详细介绍了如何通过自定义的二分查找算法来实现STL库中的lower_bound和upper_bound函数的功能,包括实现细节、代码对比及性能分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用改写二分查找的方式重写了lower_bound和upper_bound


#include <algorithm>
#include <cstdio>
#include <ctime>
using namespace std;

const int N = 55;
int a[N];

// search in a[first, last)

int my_binary_search(int first, int last, int v)
{
    int mid;
    --last;
    while(first <= last) {
        mid = (first + last) >> 1;
        if(a[mid] == v) return mid;
        else if(a[mid] > v) last = mid - 1;
        else first = mid + 1;
    }
    return -1;
}

int my_lower_bound(int first, int last, int v)
{
    int mid;
    while(first < last) {
        mid = (first + last) >> 1;
        if(a[mid] < v) first = mid + 1; // 若中位数的值小于v的值,我们要在右边子序列中查找,
                                        // 这时候pos可能是右边子序列的第一个
        else last = mid;                // 若中位数的值大于等于v,我们要在左边子序列查找,
                                        // 但有可能mid处就是最终位置,所以我们不移动last,
    }                                   // 而是让first不断逼近last。
    return first;                       // 和return last等效
}

int stl_lower_bound(int first, int last, int v)
{
    int mid, half, len = last - first;
    while(len > 0) {
        half = len >> 1;
        mid = first + half;
        if(a[mid] < v) {
            first = mid + 1;
            len = len - half - 1;       // 在右边子序列中查找
        }
        else len = half;                // 在左边子序列(包含mid)中查找
    }
    return first;
}

int my_upper_bound(int first, int last, int v)
{
    int mid;
    while(first < last) {
        mid = (first + last) >> 1;
        if(a[mid] > v) last = mid;      // 当中位数大于v时,last不动,让first不断逼近last
        else first = mid + 1;           // 当中位数小于等于v时,将first递增,并记录新的位置
    }
    return first;                       // 和return last等效
}

int stl_upper_bound(int first, int last, int v)
{
    int mid, half, len = last - first;
    while(len > 0){
        half = len >> 1;
        mid = first + half;
        if(a[mid] > v)                  // 中位数大于v,在包含last的左半边序列中查找。
            len = half;
        else{
            first = mid + 1;            // 中位数小于等于v,在右半边序列中查找。
            len = len - half - 1;
        }
    }
    return first;
}

int main()
{
    srand(time(0));
    for(int i = 0; i < N; ++i)
        a[i] = rand() % 200;
    sort(a, a + N);
    int a1, b1;
//    for(int i = 0; i < 21; ++i) {
//        printf("i : %d, value : %d\n", i, my_binary_search(0, 10, i));
//    }

//    for(int i = 0; i < 205; ++i) {
//        printf("i : %d, v1 : %d, v2 : %d", i, a1 = my_lower_bound(0, N, i), b1 = lower_bound(a, a + N, i) - a);
//        printf(", equal : %s\n", a1 == b1 ? "Yes" : "No");
//        if(a1 != b1) break;
//    }

    for(int i = 0; i < 205; ++i) {
        printf("i : %d, v1 : %d, v2 : %d", i, a1 = my_upper_bound(0, N, i), b1 = upper_bound(a, a + N, i) - a);
        printf(", equal : %s\n", a1 == b1 ? "Yes" : "No");
        if(a1 != b1) break;
    }
    return 0;
}






<think>我们正在讨论C++标准库中的`lower_bound``upper_bound`函数。这两个函数通常用于已排序的序列(如数组、向量等),以进行高效的二分查找。它们定义在`<algorithm>`头文件中。 ### 1. lower_bound - **功能**:在已排序的序列中查找第一个**大于或等于**给定值的元素的位置。 - **返回值**:返回一个迭代器,指向第一个不小于(即大于或等于)给定值的元素。如果找不到这样的元素,则返回指向序列末尾的迭代器。 - **示例**:在数组`[1, 2, 3, 3, 5]`中查找值`3`,`lower_bound`将返回指向第一个`3`的迭代器(即索引2)。 ### 2. upper_bound - **功能**:在已排序的序列中查找第一个**大于**给定值的元素的位置。 - **返回值**:返回一个迭代器,指向第一个大于给定值的元素。如果找不到这样的元素,则返回指向序列末尾的迭代器。 - **示例**:在同一个数组`[1, 2, 3, 3, 5]`中查找值`3`,`upper_bound`将返回指向`5`的迭代器(即索引4)。 ### 3. 区别 - `lower_bound`返回的是第一个**不小于**给定值的位置,而`upper_bound`返回的是第一个**大于**给定值的位置。 - 对于同一个值,`upper_bound`返回的位置一定不会小于`lower_bound`返回的位置。 - 特别地,如果序列中没有给定值,那么`lower_bound``upper_bound`会返回相同的位置,即第一个大于给定值的位置(也就是该值应该插入的位置,以保持有序)。 ### 4. 使用示例 以下是一个C++代码示例: ```cpp #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 3, 5}; int value = 3; // 使用lower_boundupper_bound auto lower = std::lower_bound(vec.begin(), vec.end(), value); auto upper = std::upper_bound(vec.begin(), vec.end(), value); // 输出位置(索引) std::cout << "lower_bound at position: " << (lower - vec.begin()) << std::endl; // 输出2 std::cout << "upper_bound at position: " << (upper - vec.begin()) << std::endl; // 输出4 // 遍历[lower_bound, upper_bound)之间的元素(即所有等于value的元素) for (auto it = lower; it != upper; ++it) { std::cout << *it << " "; // 输出3 3 } return 0; } ``` ### 5. 注意事项 - 序列必须是已排序的,否则结果未定义。 - 这两个函数的时间复杂度为$O(\log n)$,因为内部使用二分查找实现。 - 它们也可以用于自定义比较函数,以支持不同的排序方式或自定义类型。 §§相关问题§§ 1. `lower_bound``upper_bound`在自定义比较函数时如何使用? 2. 如何利用`lower_bound``upper_bound`计算有序序列中某个值的出现次数? 3. 在非降序序列中,`lower_bound``upper_bound`与在非升序序列中的使用有何不同? 4. 除了数组向量,`lower_bound``upper_bound`还可以用于哪些容器?</think>### C++中`lower_bound``upper_bound`的用法与区别 #### 1. 基本功能 - **`lower_bound`**:在**有序序列**中查找第一个**大于或等于**目标值的元素位置 公式:$\text{lower\_bound}(v) = \min\\{i \mid a_i \geq v\\}$ - **`upper_bound`**:在**有序序列**中查找第一个**大于**目标值的元素位置 公式:$\text{upper\_bound}(v) = \min\\{i \mid a_i > v\\}$ #### 2. 使用前提 - **必须对有序序列操作**(升序或自定义排序) - 包含头文件:`#include <algorithm>` - 时间复杂度:$O(\log n)$(二分查找实现) #### 3. 函数原型 ```cpp // 默认比较版本 template <class ForwardIt, class T> ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value); template <class ForwardIt, class T> ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value); // 自定义比较版本 template <class ForwardIt, class T, class Compare> ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value, Compare comp); ``` #### 4. 关键区别 | 函数 | 返回值含义 | 目标值存在时 | 目标值不存在时 | |---------------|------------------------------|--------------------------|--------------------------| | `lower_bound` | **首个 ≥ 目标值**的元素位置 | 指向第一个目标值 | 指向第一个 > 目标值的位置 | | `upper_bound` | **首个 > 目标值**的元素位置 | 指向目标值**之后**的位置 | 同左 | #### 5. 使用示例 ```cpp #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> v = {10, 20, 30, 30, 40, 50}; int target = 30; // 查找范围 [begin, end) auto low = std::lower_bound(v.begin(), v.end(), target); auto up = std::upper_bound(v.begin(), v.end(), target); std::cout << "lower_bound at index: " << (low - v.begin()) // 输出2 << "\nupper_bound at index: " << (up - v.begin()); // 输出4 // 获取所有等于target的元素范围 [low, up) for (auto it = low; it != up; ++it) { std::cout << *it << " "; // 输出30 30 } } ``` #### 6. 实际应用场景 1. **有序数据查找** ```cpp // 检查元素是否存在 bool exists = std::binary_search(v.begin(), v.end(), value); ``` 2. **插入位置确定** ```cpp v.insert(std::lower_bound(v.begin(), v.end(), new_value), new_value); ``` 3. **统计元素出现次数** ```cpp int count = std::upper_bound(v.begin(), v.end(), value) - std::lower_bound(v.begin(), v.end(), value); ``` 4. **范围查询**(如数据库查询) ```cpp auto low = std::lower_bound(data.begin(), data.end(), min_val); auto up = std::upper_bound(data.begin(), data.end(), max_val); ``` #### 7. 自定义比较函数 ```cpp struct Person { int id; std::string name; }; // 按id升序排序 auto comp = [](const Person& a, int b) { return a.id < b; }; std::vector<Person> people = {{3, "Alice"}, {5, "Bob"}, {7, "Charlie"}}; auto pos = std::lower_bound(people.begin(), people.end(), 5, comp); // 找到Bob ``` > **关键点总结**: > - `lower_bound`返回**首个 ≥ 目标**的位置,`upper_bound`返回**首个 > 目标**的位置 > - 两者配合可精确锁定值域范围 $[\text{lower\_bound}, \text{upper\_bound})$ > - 操作前**必须确保序列有序**,否则行为未定义 > - 自定义类型需提供比较函数(与排序规则一致)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值