简体   繁体   中英

Find position of a number in array closest to given number

I am searching for an elegant way to find the closest element in an array to a given value.

Here is a working implementation:

std::vector<double> array = { /* numbers */ };
double num = /* given number */;
double min_diff = std::abs(array[0] - num);
size_t best_pos = 0;
for (size_t i = 1; i < array.size(); i++) {
    double curr_diff = std::abs(array[i] - num);
    if (curr_diff < min_diff) {
        min_diff = curr_diff;
        best_pos = i;
    }
}
std::cout << best_pos << std::endl;

Is there a better solution (not algorithmically, but more beautiful)? Maybe with <algorithm> ?

There is no restriction on best_pos type, it can be std::iterator .

To find the element that minimizes some function you can use std::min_element . Note that this isn't the most efficient, as it evaluates the function to be minimized for every comparison. When the function to be minimized is more costly, you'd maybe rather populate a container of the functions results and then find the minimum in that. Though as long as it is merely a call to std::abs that should be fine:

#include <vector>
#include <iostream>
#include <algorithm>

int main(){ 
    std::vector<double> vect = { 1,2,3,6,7,8 };
    double num = 4;
    auto it = std::min_element(vect.begin(),vect.end(),[num](double x,double y){ 
        return std::abs(num-x) < std::abs(num-y); 
    });
    std::cout << *it << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM