下限误差

Lower bound error

本文关键字:误差      更新时间:2023-10-16

我在C++Lower_bound()上学习本教程。我制作了一个简单的代码来查找向量中的一个数字,该向量小于或等于向量中的数字+我想要的任何数字。我的代码是这样的

cout << *lower_bound(A.begin(), A.end(), A[x] + 3);

对向量A[]进行排序的位置。但是代码将其指向一个大于两个数字之和的数字。

例如,如果我的向量具有0, 3, 5, 8, 12的值,并且我希望它打印小于或等于A[3] + 3 = 11的最接近的数字,它应该给出8输出,但它给出12的输出。有什么原因吗?

这是我的代码:

#include <bits/stdc++.h>
using namespace std;
int main() {
    vector<int> A = {0, 5, 3, 12, 8};
    sort(A.begin(), A.end());
    cout << "A[3] = " << A[3] << endl;
    cout << *lower_bound(A.begin(), A.end(), A[3] + 3) << endl;
    return 0;
}

lower_bound

返回一个迭代器,指向区域 [first,last( 中的第一个元素,该元素的比较不小于 val。

在您的情况下,它不会返回小于 11 的最后一个值。它返回第一个不小于 11 的值,在您的示例中为 12。

如果你希望最大的数字不大于你的目标,你可以使用std::greater<>和反向迭代器(或按std::greater<>排序(

#include <vector>
#include <iostream>
#include <algorithm>
int main() {
    std::vector<int> A = {0, 5, 3, 12, 8};
    std::sort(A.begin(), A.end());
    std::cout << "A[3] = " << A[3] << std::endl;
    std::cout << *std::lower_bound(A.rbegin(), A.rend(), A[3] + 3, std::greater<int>{}) << std::endl;
    return 0;
}