Get the index of the closest value in a vector, with very small values in C++

189 views Asked by At

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

There are 0 answers