Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for nearest value in an array of doubles in C++?

Tags:

c++

search

stl

I have a sorted array of double values in C++. Is there an STL function that will return the index of the nearest value in the array to a given double value?

For example, given the following array

double myarray[5] = { 1.0, 1.2, 1.4. 1.5, 1.9 };

the function call

search(myarray, 1.6);

should return 3, the index of the element nearest to 1.6, instead of -1 (or some other flag value) indicating that the value 1.6 wasn't found.

like image 756
Bill the Lizard Avatar asked Mar 30 '09 18:03

Bill the Lizard


1 Answers

maybe std::lower_bound std::upper_bound will help you.

like image 152
bayda Avatar answered Sep 23 '22 23:09

bayda