0

I'm tryng to write a function that, given a sorted ascending vector vec and given a value value_vec[i], it gives me back the position of the element of the vector which is closer to the value.

std::vector <long double> vec { 0.0001, 0.0004, 0.004, 0.008, 0.02, 0.05};
std::vector<long double> value_vec {0.00739778,0.0103579,0.00055389} 

for (int i=0; i<value_vec.size(); i++){

  int indx= somefunction(vec, value_vec[i]);
  cout <<"Value " << value_vec[i] << " is closer to "<< vec[indx] << "element at index " << indx <<  endl;
}

I read many questions&answers about this topic, and I tried so many algorithms, but none of them seem to work in my specific case, where the number are really small. Thank you in advance for your help.

EDIT: I want to mention that I tried many algorithms similar to this one, with std::lower_bound, taken from this forum, but they don't work for me. This is why I'm asking for help.

int index_closest(std::vector<long double>::iterator begin, std::vector<long double>::iterator end, long double value) {
   
    auto it = std::lower_bound(begin, end, value, std::greater<long double>());
   
    if ( it == begin )
        return 0;
    if (it == end)
        return std::distance(begin, end) - 1;

    double diff1 = abs(value - *it);
    double diff2 = abs(value - *(it-1));
    if (diff2 < diff1){        
      return std::distance(begin, it);
    }    
    else{
      --it;
      return std::distance(begin,it);
    }    
}
fslack
  • 189
  • 9
  • Perhaps you're looking for something like [`std::lower_bound`](https://en.cppreference.com/w/cpp/algorithm/lower_bound) or [`std::upper_bound`](https://en.cppreference.com/w/cpp/algorithm/upper_bound)? – Some programmer dude Oct 07 '20 at 11:42
  • Tried but don't work in my case. – fslack Oct 07 '20 at 11:52
  • Please elaborate on "don't work". *How* doesn't it work? What is the expected result? What is the actual result? Have you tried to step through the code in a debugger to see if you can see something wrong? – Some programmer dude Oct 07 '20 at 11:56
  • 1
    If you feed the values of `vec` into the function `index_closest`, then you must use `less` in the call to `lower_bound`, because your vector is sorted in numerically increasing order. Otherwise, the preconditions of `lower_bound` are violated, and you get garbage. – j6t Oct 07 '20 at 11:59
  • Yes, you're right, but if I know myself I wouldn't be here! The expected result would be indx={3,4,1}, but It gives me idx={5,0,5}, basically it seems that value_vec elements are closer to the fist or the last elements in vec. – fslack Oct 07 '20 at 12:03
  • 1
    Then try again with `lower_bound` and replace `greater` with `less`. – j6t Oct 07 '20 at 12:07

0 Answers0