c++ - 有没有办法为 std::map 中小于给定键的第一个元素找到反向迭代器?

标签 c++ stl iterator stdmap lower-bound

我在 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.

关于c++ - 有没有办法为 std::map 中小于给定键的第一个元素找到反向迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9503489/

相关文章:

c++ - “cl”不被识别为内部或外部,vcvarsall

c++ - 来自 std::basic_string 的私有(private)继承

c++ - g++ : should --std option change which STL/stdlib my code uses?

c++ - "auto changes meaning in c++11"

c++ - 使用 OpenCV 将帧转换为就像从上方获取的一样

c++ - i7 处理器与 windows8 操作系统的多线程问题

c++ - 使用 const 对象 move 语义

c++ - 几个模板问题(已经解决了...只是想知道为什么)

c++ - 使用迭代器时如何解决 "Access Violation"?

c++ - std::begin 可以使用数组参数吗?如果可以,如何?