循环遍历数组并找到最靠近键的数组元素的最佳方法是什么?

Nic*_*ick 1 c++ visual-c++

到目前为止,这是我的代码,我被困住了.就绝对值而言,最接近7的值是5.如何检查数组的每个元素以查看它是否是最接近的元素,然后返回该值.我知道这可能比我想象的要容易,但我是编程的初学者.

#include <iostream>
#include <cmath>
using namespace std;

const int MAX = 25;

int searchArray(int [], int); \\prototype

int main(){

    int numArray[MAX] ={1,4,5,10,11,12,13,14,15,16,17,18,19,20,35,26,43,15,48,69,32,45,57,98,100};

searchArray(numArray, 7);
system("pause");
return 0;
}


int searchArray(int a[], int b){

int distance = 0;

for(int i=0;i<MAX;i++){
    if(i==b)
        return i;
    else if(i<b || i > b)
        abs(distance) == i-b;
    return distance;


}

}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 6

您可以使用std::min_element:

#include <iostream>
#include <algorithm>
#include <cstdlib>

int main()
{
   int numArray[] ={1,4,5,10,11,12,13,14,15,16,17,18,19,20,35,26,43,15,48,69,32,45,57,98,100};

   //find nearest element to key            
   int key = 7;
   auto cmp = [&](int a, int b) { return std::abs(key-a) < std::abs(key-b); };
   int nearest_value = *std::min_element(std::begin(numArray),std::end(numArray),cmp);

   std::cout << nearest_value << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

输出(演示):

5
Run Code Online (Sandbox Code Playgroud)