使用upper_bound返回严格较小的元素

时间:2015-08-12 02:44:02

标签: c++

我想在数组中找到小于K的最大元素。我正在尝试使用upper_bound()函数:

upper_bound(a,a+n,k, std::greater<int>());

对于int a[4] = {1, 2, 3, 4};int k = 3;,我希望输出为1,因为a[1] = 2是小于k的最大元素。

但是,上述比较器的输出为4。我怎么能为此编写自己的比较器?

1 个答案:

答案 0 :(得分:1)

相当于

std::lower_bound(v.begin(), v.end(), v, std::less<>{})
std::upper_bound

是:

std::upper_bound(v.rbegin(), v.rend(), v, std::greater<>{}).base();

所有事情都颠倒过来(从结束,相反的顺序看)。

Live Demo