到目前为止,这是我的代码,我被困住了。就绝对值而言,最接近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;
}
}
答案 0 :(得分: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;
}
输出(demo):
5
答案 1 :(得分:3)
将搜索功能写入以下内容:
int searchArray(int a[], int b){
int min_dist = 0; // keep track of mininum distance seen so far
int min_index = 0; // keep track of the index of the element
// that has the min index
for( int i = 0; i < a.Length; i++ ){ // a.Length is the size of the array
if( a[i] == b ) { // if we find the exact one, stop
return i;
} else { // otherwise, keep looking for the closest
if ( abs(a[i] - b) < min_dist ) { // if this one is closer, update
min_dist = abs(a[i] - b);
min_index = i;
}
}
}
return min_index; // when we finish return the index of the closest
}
答案 2 :(得分:3)
您可以使用标准算法为您执行此操作:
struct closer_to
{
int target_;
explicit closer_to( int target ) : target_( target ){}
bool operator ()( int left, int right ) const
{
return std::abs( target_ - left ) < std::abs( target_ - right );
}
};
int* iter =
std::min_element(
numArray + 0, numArray + MAX
, closer_to( 7 )
);
min_element
会将迭代器(在本例中为指针)返回到第一个元素, Container 中没有其他元素是{{ 1}}。
使用 C ++ 11 和lambdas,它看起来像这样:
closer_to( 7 )
答案 3 :(得分:1)
您必须将您的号码与阵列上的每个号码进行比较,并跟踪到目前为止的最小距离。
int searchArray(int a[], int b){
int minDistance = -1;
for(int i=0;i<MAX;i++){
if(minDistance == -1 || abs(minDistance - b) > abs(a[i] - b))
minDistance = a[i];
}
return minDistance;
}