Is there a way to find a reverse iterator for the first element in a std::map less than a given key?
-
14-11-2019 - |
Question
I came across the following code snippet in C++ (I am not yet on 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;
}
In particular, I do not like the use of --itr
at the end nor the compare of itr
to begin()
, they both feel wrong to me.
I'm wondering if there is a way with STL to do some kind of lookup that would return end() (or rend()) if not found and otherwise to return the last element that is less than or equal to the value
so the code would look more like this:
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;
}
In a sense, I want a reverse_lower_bound() that returns a reverse iterator to the last element that is not greater than the value
or if none can be found rend().
Solution
Based on Xeo's comment, I think this is the answer:
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;
}
I learned this new thing:
When an iterator is reversed, the reversed version does not point to the same
element in the range, but to the one preceding it.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow