Is there a single one-liner to find the largest element smaller than some element x in a sorted container? I'm essentially interested in any code that will give me an iterator pointing to the largest element smaller than x.
I know how to code this up myself, but would hope that there is a library function for it...
EDIT: Maybe I should make myself clear here, that the version I have in mind that I would code myself is based on binary search and thus runs in O(log n) time. I need to compute this for lists with up to a few million elements.
Since your container is sorted, you can use std::max_element
on a range ending with the first element greater than your max, use std::find_if
with a lambda, or std::lower_bound
to get this range :
int main()
{
std::set<int> s{ 3, 1, -14, 1, 5, 9 };
std::set<int>::iterator result;
int max_value = 6;
result = std::max_element(std::begin(s), std::find_if(std::begin(s), std::end(s), [&](int i) { return i >= max_value; } ) );
std::cout << "max element is: " << *result;
}
Output :
max element is: 5
Live Demo
Or with std::lower_bound
:
int main()
{
std::set<int> s{ 3, 1, -14, 1, 5, 9 };
std::set<int>::iterator result;
int max_value = 6;
result = std::max_element(std::begin(s), std::lower_bound(std::begin(s), std::end(s), max_value)) ;
std::cout << "max element is: " << *result;
}
Live Demo
You can just use
lower_bound(container.begin(), container.end(), currentElement);
Now if that is different than container.begin()
then there is an element that is smaller than your current one, just substract one and you get it. If you are sure there is always such an element just do
lower_bound(container.begin(), container.end(), currentElement) - 1;
EDIT: Of course I assume that your iterator is bidirectional.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With