【问题标题】:Is there a function like lower_bound that returns the last value instead of the first?有没有像 lower_bound 这样返回最后一个值而不是第一个值的函数?
【发布时间】:2018-08-10 13:02:09
【问题描述】:

例如,如果我有一个排序数组

{1,1,1,1,1,4,5}

我想知道1 的最右边的索引,有没有一个函数可以让我这样做? (除了对数组进行反向排序)

【问题讨论】:

  • std::upper_bound - 1
  • 我确实考虑过upper_bound,但它并没有完成我想做的事情。
  • @Justin 那不是给他 5 的索引吗?
  • 使用upper_bound并有条件地将索引减一

标签: c++ arrays function sorting


【解决方案1】:

这应该可行:

auto p = std::equal_range( std::begin(v), std::end(v), 1 );
if( p.first != p.second ) {
    auto it = p.second - 1;
    //...
}

live example

【讨论】:

    【解决方案2】:

    没有,所以你应该自己制作一个。

    template<class Ctr, class Elem> auto rightmost(Ctr &&c, Elem &&e) {
        using std::begin;
        using std::end;
        auto b{begin(c)};
        auto retVal{std::upper_bound(b, end(c), e)};
        return retVal == b? b : --retVal;
    }
    

    【讨论】:

      【解决方案3】:
      #include <iostream>
      #include <array>
      #include <algorithm>
      #include <iterator>
      
      int main()
      {
          std::array<int, 6> data({2,2,2,2,4,7});
      
          auto it = std::upper_bound(data.begin(), data.end(), 2);
          int index = std::distance(data.begin(), it) - 1;
      
          std::cout << "index for last '2' is " << index << std::endl;
      }
      

      输出:
      index for last '2' is 3

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        • 1970-01-01
        相关资源
        最近更新 更多