【问题标题】:An algorithm like lower_bound(), but another一个类似lower_bound()的算法,但是另一个
【发布时间】:2016-01-06 13:05:02
【问题描述】:

有一个upper_bound(),返回一个迭代器到第一个大于大于val的元素。

有一个lower_bound(),返回一个迭代器到第一个不小于小于val的元素。

是否有一种算法可以将迭代器返回到不大于大于 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 ;
}

输出:1,扩展 3

请注意,像 std::greater&lt;&gt; 这样的另一个谓词不起作用。

【问题讨论】:

  • 如何为lower_bound 使用不同的谓词,例如std::greater&lt;&gt;
  • 使用reverse_iterator...
  • upper_bound(..) - 1
  • @Jarod42,看来不错,谢谢
  • @Jarod42 upper_bound() 与前向迭代器一起使用,因此在某些情况下可能不起作用

标签: c++ algorithm


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我的两位,你忘了按降序排序。

    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
    

    或使用 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
    

    【讨论】:

      猜你喜欢
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多