Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find closest smaller number in array with C++?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}

See live demo

I leave the error handling for you.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading