下限误差

Lower bound error

我正在关注 this 关于 Lower_bound() 的 C++ 教程。我编写了一个简单的代码来查找向量中的数字小于或等于向量中的数字 + 我想要的任何数字。我的代码是这样的

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

Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.

在您的情况下,它不会返回小于 11 的最后一个值。它 returns 第一个值 而不是 小于 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;
}