【问题标题】:Is there a way to find a reverse iterator for the first element in a std::map less than a given key?有没有办法为 std::map 中小于给定键的第一个元素找到反向迭代器?
【发布时间】:2012-02-29 17:08:14
【问题描述】:

我在 C++ 中遇到了以下代码 sn-p(我还没有使用 C++11):

int test(std::map<int, size_t> &threshold, const int value) {
  std::map<int, size_t>::const_iterator itr = threshold.upper_bound(value);

  if (threshold.begin() == itr) {
    return -1;
  }
  return return (--itr)->second;
}

特别是,我不喜欢最后使用--itr,也不喜欢itrbegin()的比较,他们都觉得我不对。

我想知道 STL 是否有办法进行某种查找,如果未找到将返回 end()(或 rend()),否则返回小于或等于的最后一个元素value 所以代码看起来更像这样:

int test(std::map<int, size_t> &threshold, const int value) {
  std::map<int, size_t>::const_reverse_iterator itr = threshold.WhatGoesHere(value);

  if (threshold.rend() == itr) {
    return -1;
  }
  return return itr->second;
}

从某种意义上说,我想要一个 reverse_lower_bound(),它返回一个反向迭代器到最后一个不大于 value 的元素,或者如果没有找到 rend()。

【问题讨论】:

  • 我撤回我的评论,它不会是一样的。我目前正在寻找答案。
  • 即使您不喜欢刚开始使用的代码,但对我来说它看起来还不错。将迭代器与 begin() 进行比较并没有错,将其递减也没有错。
  • @Mark:你确定吗? IIRC,lower_bound 返回等于或大于,而 upper_bound 返回严格大于。
  • @Xeo,是的,我搞砸了。删除我的评论。
  • @Xeo 考虑到反转迭代器为您提供了先验元素,这对我来说看起来是正确的。注意我编辑了问题的最后一段,它与代码的行为不匹配。

标签: c++ stl iterator stdmap lower-bound


【解决方案1】:

根据 Xeo 的评论,我认为这是答案:

int test(std::map<int, size_t> &threshold, const int value) {
  std::map<int, size_t>::const_reverse_iterator
    last_element_not_greater_than(threshold.upper_bound(value));

  if (threshold.rend() == last_element_not_greater_than) {
    return -1;
  }
  return return last_element_not_greater_than->second;
}

我学到了这个新东西:

When an iterator is reversed, the reversed version does not point to the same
element in the range, but to the one preceding it.

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 2021-02-14
  • 2016-10-31
  • 2011-02-15
  • 2015-05-15
  • 2010-12-11
相关资源
最近更新 更多