我在 C++ 中遇到了以下代码片段(我还没有使用 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()。

有帮助吗?

解决方案

根据 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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top