lower_bound 的使用

使用前提:数列为有序数列。

①数组内

//查找范围:[ begin , end ) ,左闭右开区间。
*lower_bound(begin, end, num);        //返回第一个 >= num 的数的数值
lower_bound(begin, end, num) - begin; // 返回下标

实际操作:
int a[100] = {0, 1, 3, 5, 7, 9, 10};
//       下标:0  1  2  3  4  5  6
int main()
{
    int x = lower_bound(a + 1, a + 6 + 1, 6) - a; //输出下标
    int y = *lower_bound(a + 1, a + 6 + 1, 6);    //输出值
    printf("%d %d", x, y);
    return 0;
}

输出结果:4 7

②结构体内

结构体内使用 lower_bound 需要重载,下面我们主要对结构体中的 \(a\) 进行操作。

struct node //开结构体
{
    int a, id; //定义结构体内的两个变量
    node() {}
    node(int x, int y) : a(x), id(y) {}
    bool operator<(const node t) const //重载
    {
        return a < t.a;
    }
} t[1001];

bool cmp(node x, node y) //快排 cmp 比较函数
{
    if (x.a < y.a)
        return 1; //结构体内按 a 由小到大排序。
    return 0;
}

int main()
{
    int n = read(); //数列中数的个数
    for (int i = 1; i <= n; ++i)
    {
        t[i].a = read(); //读入数列
        t[i].id = i;
    }
    sort(t + 1, t + n + 1, cmp); //按小到大排序

    int x, xiabiao, ans;
    x = read();                                              //需要查找的数字
    xiabiao = lower_bound(t + 1, t + n + 1, node(x, 0)) - t; //这样求下标
    ans = (*lower_bound(t + 1, t + n + 1, node(x, 0))).a;    //这样求值
    printf("%d %d\n", xiabiao, ans);
    return 0;
}

输入:
5
20 40 30 10 50
35
输出:
4 40

另:upper_bound 的使用与 lower_bound 的使用类似,只不过是严格大于(>)。

原文地址:https://www.cnblogs.com/EdisonBa/p/14948670.html