【问题标题】:Assign return value from upper_bound to reverse_iterator [duplicate]将Upper_bound返回值分配给Reverse_iterator [复制]
【发布时间】:2017-05-02 09:01:00
【问题描述】:

我通过upper_bound 在std::map<int, X> 中找到某个点,然后从这一点开始向后迭代。我的代码看起来像:

MAP::reverse_iterator iter;

iter = _map.upper_bound(value);  // Does not compile because upper_bound is not reverse_iterator

while(iter != rbegin()){
    // logic
    --iter;
}

我得到一个编译错误,因为upper_bound() 没有返回reverse_iterator。

解决这个问题的最佳方法是什么?

【问题讨论】:

  • 将迭代器转换为反向迭代器?
  • @NathanOliver 谢谢没有意识到这是可能的。如果你把它作为答案,我会接受。

标签: c++ c++11 stl stdmap


【解决方案1】:

您需要将您的迭代器转换为反向迭代器:

auto iter = _map.upper_bound(value);
for (std::reverse_iterator<decltype(iter)> rit{iter}; rit != _map.rend(); ++rit) {
     // Do whatever you want...
}

请注意,到达_map.rend()时必须停止,而不是_map.rbegin(),并且需要递增反向迭代器,而不是递减它。

【讨论】:

  • 这是 C++14 还是 C++11?我在 GCC4.8.2 上收到编译器错误,说它无法转换 std::reverse_iterator rit{map.upper_bound(10)};
  • @user997112 这应该在 c++11 中工作。
猜你喜欢
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
  • 2019-12-31
相关资源
最近更新 更多