c++ - 遍历数组并找到最接近键的数组元素的最佳方法是什么?

标签 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;


}

}

最佳答案

您可以使用 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;
}

输出(demo):

5

关于c++ - 遍历数组并找到最接近键的数组元素的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14223463/

相关文章:

c++ - 如何创建 std::array 包装器类

c++ - 创建 Visual Studio 错误列表消息

c++ - 如何在c++中检索 vector 内的对象

c++ - C++中的继承异常和并发编程

c++ - 访问数据成员(本身是对象)的数据成员,就好像它们是类成员一样

c++ - 在 C++ 中捕获段错误

c++ - 使用 Word 的 CustomXMLPart 或任何其他支持的方式存储 UTF-8 XML

c++ - Visual C++ 2015 中已删除使用 mem_fun1() 的替代方法

c++ - 从私有(private)成员值类型 (bool) 读取的 VC++ 访问冲突

visual-c++ - 在 VC++ 中由元组索引的 map