简体   繁体   English

类似lower_bound()的算法,但是另一个

[英]An algorithm like lower_bound(), but another

There is a upper_bound() , returns an iterator to the first element that is greater than val. 有一个upper_bound() ,将迭代器返回到大于 val的第一个元素。

There is a lower_bound() , returns an iterator to the first element that is not less than val. 有一个lower_bound() ,将迭代器返回到不小于 val的第一个元素。

Is there an algorithm that returns an iterator to the first element that is not greater than val, or I have to reinvent the wheel? 是否有一种算法可以将迭代器返回不大于 val的第一个元素,否则我必须重新发明轮子了?

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    std::vector<int> data = { 1, 1, 2, 3, 3, 3, 3, 5, 5, 6 };

    auto lower = std::lower_bound(data.begin(), data.end(), 4, [](int x, int y) {return x > y;});

    cout << *lower ;
}

Output: 1, expexted 3 输出:1,扩展3

Note that another predicate like std::greater<> doesn't work. 请注意,另一个谓词(例如std::greater<>不起作用。

只需在您的代码中使用谓词,但是使用rbeginrend以相反的顺序遍历它

My two bits, you forgot to sort in descending order. 我的两位,您忘了按降序排序。

int main()
{
    vector<int> data = { 1, 1, 2, 3, 3, 3, 3, 5, 5, 6 };

    int wanted {4};
    sort(begin(data), end(data), greater<int>());
    auto bound =  upper_bound(begin(data), end(data), wanted, greater<int>());
    cout << "val with upper_bound: " << *bound << endl;


}

result:  val with upper_bound: 3

or one step below with partition_point: 或使用partition_point在下面执行以下步骤:

template <typename T>
struct greater_than {
    T x;
    bool operator()(const T& y) { return y > x; }
};

int main() 
{
 ...
 auto p_point = partition_point(begin(data), end(data),
                               greater_than<int>{wanted});

 cout << "val with partition_point: " << *p_point << endl;
// val with partition_point: 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM