c++ - 有什么方法可以对成员变量执行 std::upper_bound 吗?

标签 c++ c++17

我想使用 std::upper_bound 查找某个容器中小于或等于提供值的对象范围。这使它成为一个很好的简单的单线!

问题是我只对与类的特定原始成员进行比较感兴趣。对容器进行排序没有问题,但是当我想使用 std::upper_bound 时,我需要提供一个对象来比较该函数是否起作用。

对于 MCVE,假设我有一群人,我想找到一个迭代器来:

struct Person {
    int age;
    double height;

    Person(int age, double height) : age(age), height(height) { }
};

int main() {
    vector<Person> people = { 
        Person(5, 12.3), 
        Person(42, 9.6), 
        Person(38, 18.4), 
        Person(31, 8.5)
    };

    auto sorter = [](const Person& a, const Person& b) {
        return a.height < b.height;
    };

    std::sort(people.begin(), people.end(), sorter);

    // All I care about is comparing against this number
    // Instead... I have to create a whole new struct
    //double cutoff = 10.0;
    Person cutoff(123, 10.0);
    auto it = std::upper_bound(people.begin(), people.end(), cutoff, sorter);

    // Do stuff with 'it' here
}

我遇到的问题是我需要实例化整个对象才能使用 std::upper_bound,就像我在上面的代码中所做的那样。我无法“与我提供的值(value)进行比较”。这非常烦人,因为我要比较的对象在不做大量工作的情况下不容易出现。

是否有任何可行的策略来解决这个问题,从而生成我能找到的最干净、最紧凑的代码?例如,如果我能做到(对于 MCVE)就好了:

auto cutoffCompare = [](const Person& p, const double height) { 
    return p.height < height;
};

// Doesn't exist (AFAIK?)
auto it = std::upper_bound(people.begin(), people.end(), cutoff, sorter, cutoffCompare);

由于它处于程序中的热点,我比平时更关心性能,所以我不能做一些事情,比如将对象转换为原始类型,然后对其执行 upper_bound新列表。我可以创建一个全新的对象并将其用作虚拟对象,但随后我将添加大量烦人的代码来完成一些非常简单的事情。我是否坚持实例化对象?还是我必须滚动自己的 upper_bound?

最佳答案

没有要求传递给 std::upper_bound 的值必须匹配迭代器的类型,如果您提供正确的比较函数,它可以是您想要的任何类型。你与你想要的样本非常接近,只需要翻转参数。文档 here表示比较函数将极限值作为第一个参数。

auto cutoffCompare = [](double height, const Person& p) { 
    return p.height < height;
};

auto it = std::upper_bound(people.begin(), people.end(), 10.0, cutoffCompare);

关于c++ - 有什么方法可以对成员变量执行 std::upper_bound 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55017337/

相关文章:

c++ - 在std::function中获取std::future的结果类型

c++ - 收到 'undeclared identifier' 错误

c++ - 检查字符串是否为空

c++ - std::merge 在 C++ 中如何工作?

c++ - Busy-waiting和定时器中断在编程中的优缺点是什么?

c++ - 如何打印 std::map<int, std::vector<int>>?

C++ regex_search 在 C 样式数组上进行匹配

c++ - 如何在sigaction sa_sigaction中设置类方法?

c++ - 编写 C/C++ 守护进程 (Linux)

c++ - 调用超时方法