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().
Based on Xeo’s comment, I think this is the answer:
I learned this new thing: