下限错误

时间:2018-04-20 06:21:45

标签: c++ vector lower-bound

我在C ++中关注Lower_bound()的{​​{3}}教程。我做了一个简单的代码,在向量中找到一个小于或等于向量中的数字的数字+我想要的任何数字。我的代码就像这样

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;
}

2 个答案:

答案 0 :(得分:3)

lower_bound

  

返回指向范围[first,last]中第一个元素的迭代器,该元素的值不比val小。

在你的情况下,它没有返回小于11的最后一个值。它返回的第一个值小于11,在你的例子中是12。

答案 1 :(得分:0)

如果您希望最大数量不超过目标,可以使用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;
}
相关问题