我在 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
,也不喜欢将 itr
与 begin()
进行比较,他们都让我觉得不对。
我想知道是否有一种方法可以使用 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/