查找数组中最接近给定数字的数字的位置

时间:2021-05-26 16:25:02

标签: c++ algorithm stl

我正在寻找一种优雅的方法来查找数组中与给定值最接近的元素。

这是一个有效的实现:

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;

有没有更好的解决方案(不是算法上的,而是更漂亮的)?也许用<algorithm>

best_pos类型没有限制,可以是std::iterator

1 个答案:

答案 0 :(得分:2)

要找到最小化某些函数的元素,您可以使用 std::min_element。请注意,这不是最有效的,因为它会为每次比较评估要最小化的函数。当要最小化的函数成本更高时,您可能宁愿填充函数结果的容器,然后在其中找到最小值。不过只要只是调用 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;
}