   c++ how would you define this find() function?
  if I have an array of floats in ascending order like below:f[5] //0.1, 0.2, 0.3, 0.4, 0.5I have some key values:  v1 = 0.25;   v2 = 0.42;I want to write a function to find which values in the array are the closest to v1 and v2. In this case, for v1 result is f[2] i.e. 0.3 and for v2 result is f[3] i.e. 0.4Is there a function in the STL?Thanks in advance.   
  Although the exact thing you are asking is not provided by the STL, there is an algorithm called std::equal_range that can be used to implement what you want. If you have trouble with the implementation, I can try to write some code for you.EDIT: Actually, here's the code:#include <iostream>#include <algorithm>template <class Iterator, class T>double find(Iterator begin, Iterator end, T value) {  std::pair<Iterator, Iterator> result = std::equal_range(begin, end, value);    // Is value found exactly or lower than the first entry?  if (result.first != result.second || result.first == begin)    return *result.first;    --result.first;    // Is value higher than the last entry?  if (result.second == end)    return *result.first;    T const &lower = *result.first;  T const &upper = *result.second;  return (value-lower < upper-value) ? lower : upper;}int main() {  double f[5] = {0.1, 0.2, 0.3, 0.4, 0.5};  std::cout << find(f,f+5,0.25) << '\n';  std::cout << find(f,f+5,0.4) << '\n';} [Edited by - alvaro on May 13, 2010 7:38:29 AM];Quote:Original post by alvaroAlthough the exact thing you are asking is not provided by the STL, there is an algorithm called std::equal_range that can be used to implement what you want. If you have trouble with the implementation, I can try to write some code for you.Thanks a lot. The example in the api specification looks straight forward.;  I think you may also want to check out lower_bound, which gives the item that is equal to the one queried for, or the first that is bigger. Then you can check the previous one (if there is any) to see which one is closer. (Also take into account that it can return the end of the range, if all values are smaller.)Also, since when is 0.3 closer to 0.25 than 0.2? :)   