【问题标题】:how to use upper_bound to find out the last variable that satisfies a certain condition如何使用upper_bound找出满足某个条件的最后一个变量
【发布时间】:2020-11-11 21:28:44
【问题描述】:

我正在尝试使用 log(n) 方法找出满足特定条件的最后一个变量。我查看了文档,发现 这些在算法部分(http://www.cplusplus.com/reference/algorithm/

二分查找(在分区/排序范围内操作):

lower_bound:将迭代器返回到下界(函数模板)

upper_bound:将迭代器返回到上界(函数模板)

equal_range:获取相等元素的子范围(函数模板)

binary_search:测试值是否存在于排序序列中(函数模板)

我认为要做我想做的事,我应该使用upper_bound/lower_bound。

在这种情况下,我试图找出小于或等于 3 的数字的最后一个索引。(3)。我知道有更简单的方法,例如遍历整个数组,但我想学习如何使用 upper_bound。我知道比较器需要 2 个数字,但我不需要 2 个数字,所以我不知道该怎么做。

#include <bits/stdc++.h>

using namespace std;
vector<int> a = {0,1,2,3,4,5};
bool check(int base) {
    if (a.at(base)  <= 3) {
        return true;
    }
    return false;
}

int main() {
    int c;
    sort(a.begin(), a.end());
    c = distance(a.begin(), upper_bound(a.begin(), a.end(), check));
    cout<<c;
    return 0;
}

我该如何正确地做到这一点?

【问题讨论】:

    标签: c++ c++11 c++14 c++17


    【解决方案1】:

    比较器将您正在搜索的数字3 与向量中的数字进行比较。这就是为什么它需要两个参数。当您应该将其作为参数传递给 upper_bound 时,您已经在比较器中硬编码了数字 3

    它也是对向量排序的函数,所以如果你要使用一个,你也应该把它传递给sort

    您的代码可能如下所示

    bool check(int x, int y) {
        return x < y;
    }
    
    int main() {
        int c;
        sort(a.begin(), a.end(), check);
        c = distance(a.begin(), upper_bound(a.begin(), a.end(), 3, check));
    }
    

    但由于在这种情况下check 只是默认的小于运算,因此您可以完全省略它。

    int main() {
        int c;
        sort(a.begin(), a.end());
        c = distance(a.begin(), upper_bound(a.begin(), a.end(), 3));
    }
    

    见参考here

    【讨论】:

    • x 或 y 的值是 3 吗?
    • @RonaldLiu 这是x。但请注意,它必须是 小于 运算符。如果在排序的向量中将 x 放在 y 之前,则应该为 true,否则为 false。
    猜你喜欢
    • 1970-01-01
    • 2018-05-05
    • 2017-01-03
    • 2018-02-02
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    相关资源
    最近更新 更多