我想使用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
来实例化整个对象,就像在上面的代码中一样。我不能“与我提供的价值进行比较”。这使我非常烦恼,因为要进行比较的对象很难在不进行大量工作的情况下突然出现。
是否有任何可行的策略可以解决这个问题,从而使我找到最干净,最紧凑的代码?例如,如果我能做的很好(对于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?
答案 0 :(得分:4)
不要求传递给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);