Consider this array:
std::vector<int> numbers = { 0, 4, 12, 60, 89 };
It is sorted and only has positive numbers.
What is the easiest way to find closest smaller number in the array, preferably from <algorithm>? Example:
| Number | Result |
|---|---|
| 0 | 0 |
| 3 | 0 |
| 15 | 12 |
| 74 | 60 |
| 150 | 89 |
>Solution :
What is the easiest way to find closest smaller number in the array, preferably from
<algorithm>?
You are looking for the std::lower_bound (or std::ranges::lower_bound since C++20). Check the example code given in the referenced page.
For instance, you could write a function as follows:
#include <algorithm> // std::ranges::lower_bound
auto find_closest(std::vector<int> const& numbers, int query)
{
auto it = std::ranges::lower_bound(numbers, query);
// Handle negative values
return (it == std::cbegin(numbers)) ? *it : *(--it);
}
I leave the error handling for you.