Is there a function in that uses binary search, like lower_bound
but that returns the last item less-than-or-equal-to according to a given predicate?
lower_bound
is defined to:
Finds the position of the first element in an ordered range that has a value greater than or equivalent to a specified value, where the ordering criterion may be specified by a binary predicate.
and upper_bound
:
Finds the position of the first element in an ordered range that has a value that is greater than a specified value, where the ordering criterion may be specified by a binary predicate.
Specifically, I have a container of time ordered events and for a given time I want to find the last item that came before or at that point. Can I achieve this with some combination of upper/lower bound, reverse iterators and using std::greater
or std::greater_equal
?
EDIT: A tweak was needed to user763305's suggestion to cope with if you ask for a point before the start of the array:
iterator it=upper_bound(begin(), end(), val, LessThanFunction());
if (it!=begin()) {
it--; // not at end of array so rewind to previous item
} else {
it=end(); // no items before this point, so return end()
}
return it;
std::greater
you'd first have to either reverse the range or use a reverse iterator over it. And you can't ever usestd::greater_equal
as a comparator because it is not a strict weak order. – Geographer