简体   繁体   English

在数组中找到最接近给定数字的数字的 position

[英]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> ?也许与<algorithm>

There is no restriction on best_pos type, it can be std::iterator . best_pos类型没有限制,可以是std::iterator

To find the element that minimizes some function you can use std::min_element .要找到最小化某些 function 的元素,您可以使用std::min_element Note that this isn't the most efficient, as it evaluates the function to be minimized for every comparison.请注意,这不是最有效的,因为它评估 function 以在每次比较时最小化。 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.当要最小化的 function 成本更高时,您可能宁愿填充函数结果的容器,然后在其中找到最小值。 Though as long as it is merely a call to std::abs that should be fine:虽然只要它只是对std::abs的调用就应该没问题:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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