STL利器:upper_bound与lower_bound的使用

upper_bound 用于在已排序的序列中查找第一个大于给定值的元素位置。

基本语法

cpp 复制代码
// 在 [first, last) 范围内查找第一个大于 value 的元素
auto it = upper_bound(first, last, value);

与相关函数的对比

|-------------|--------------------|-----|
| 函数 | 作用 | 返回值 |
| lower_bound | 第一个大于等于​ value 的元素 | 迭代器 |
| upper_bound | 第一个大于​ value 的元素 | 迭代器 |

示例代码:

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> nums = {1, 2, 2, 3, 3, 3, 4, 5};
    
    // 查找第一个大于 3 的元素
    auto it = upper_bound(nums.begin(), nums.end(), 3);
    auto it2 = lower_bound(nums.begin(), nums.end(), 3);
    
    if (it != nums.end()) {
        cout << "第一个大于3的元素是: " << *it << endl; // 输出 4
        cout << "位置索引: " << it - nums.begin() << endl; // 输出 6
    }
    cout<<"---------------------------------"<<endl;
    if (it2 != nums.end()) {
        cout << "第一个大于等于3的元素是: " << *it2 << endl; // 输出 3
        cout << "位置索引: " << it2 - nums.begin() << endl; // 输出 3
    }
    
    return 0;
}

注意点:

1)upper_bound只能在已排序的序列上工作

2)返回值是迭代器:需要转换为索引或直接使用

3)时间复杂度:O(log n) 的二分查找,很高效

4)边界检查:记得检查返回值是否等于 end(),表示没找到

相关推荐
fqbqrr2 小时前
2606C++,C++构的多态
开发语言·c++
小欣加油2 小时前
leetcode56 合并区间
c++·算法·leetcode·职场和发展
Yolo_TvT3 小时前
C++:析构函数
c++
Hello:CodeWorld5 小时前
C 风格变参 vs C++ 变参模板:核心区别与选型指南
c语言·c++·算法
搬砖魁首7 小时前
基础能力系列 - 多线程2 - 条件变量
c++·rust·条件变量·原子类型·线程同步互斥
chase_my_dream7 小时前
C++ + SLAM 高频面试问题整理
开发语言·c++·面试
牛油果子哥q7 小时前
【C++ STL string 】C++ STL string 终极精讲:底层原理、内存机制、全套API、深浅拷贝、易错坑点与工程实战规范
数据库·c++
凡人叶枫9 小时前
Effective C++ 条款04:确定对象被使用前已先被初始化
java·linux·开发语言·c++·嵌入式开发
不想写代码的星星9 小时前
std::move 根本不移动,就像老婆饼里没有老婆
c++
redaijufeng9 小时前
C++雾中风景7:闭包
c++·算法·风景