C ++最近的数组搜索

时间:2015-10-26 05:22:44

标签: c++ arrays function search random

好的,为了我的作业,我必须在其中创建一个包含5个随机值的数组,询问用户要搜索的数字,然后返回搜索到的数字的索引。所有这一切都很容易(或者至少我已经完成了),但现在如果用户输入的数字在数组中不存在,那么我仍然必须返回最接近它的数字。

示例1:

Int iArr[SIZE] = {45, 38, 198, 36, 781};

Int iSearchTarget = 199;

退回指数= 2(指数为198)

示例2:

Int iArr[SIZE] = {45, 38, 198, 36,781};

Int iSearchTarget = 37;

退回指数= 1(指数为38)

... 这是我的函数的样子,我只需要帮助你找到“最近”而不是返回-1。

int searchList(const int list[], int numElems, int value)
{
    int index = 0;
    int position = -1;
    bool found = false;

    while (index < numElems && !found)
    {
        if (list[index] == value)
        {
            found = true;
            position = index;
            cout << "The index of the number you searched for is "<<     position << endl;
        }
        index++;
    }

    if (position == -1) {
        cout<<"Search not found" << position<<endl;
    }
    return position;

}

4 个答案:

答案 0 :(得分:1)

这是我采取的方法。

我首先要存储第一个数组项(0)的索引,以及该项与iSearchTarget之间的绝对差值。

接下来,我将循环遍历数组的其余部分,并且对于任何与iSearchTarget的绝对差异小于当前存储的项目,我会用该新项目替换索引和差异。“ p>

完成后,您将拥有最近项目的索引。

但很抱歉,我没有为你编写代码。

答案 1 :(得分:0)

在每次迭代后,在搜索时取另一个变量(min),该变量存储数字的绝对差值

for(i=0;i<n;i++)
{
 if(arr[i]==iSearchTarget)
 { 
  //found 
 }
 else
 {
   p=abs(arr[i]-iSearchTarget) //absolute value of the difference
   if(p<min)
   {
    min=p;
    index=i;
   }
 }
}
// print the index or the difference according to your requirement

P.S。它只是一个关于如何处理问题的想法。没有完整的代码

答案 2 :(得分:0)

我的方法就是这样......

#include <iostream>

using namespace std;

const int cSize = 5;
int iArr[cSize] = { 45, 38, 198, 36,781 };

int searchList(const int list[], int numElems, int value) {
    int diff = abs(list[0] - value) , idx{ 0 };
    for (int i = 0; i < numElems; i++) {
        if (abs(list[i] - value) < diff) {
            diff = abs(list[i] - value);
            idx = i;
        }
    }
    return list[idx];
}

int main() {

    int num{ 0 };
    cout << "Please enter an integer: ";
    cin >> num;

    cout << "The closest number is: " << searchList(iArr, cSize, num) << endl;

    // system("pause");
    return 0;
}

答案 3 :(得分:0)

使用算法,它变为:

#include <algorithm>
#include <iostream>

int searchNearest(const int (&a)[5], int value) {
    auto it = std::min_element(std::begin(a), std::end(a),
                               [value](int lhs, int rhs) {
                                   return std::abs(lhs - value) < std::abs(rhs - value);
                               });
    return std::distance(std::begin(a), it);
}

int main() {
    int arr[] = { 45, 38, 198, 36,781 };
    int num = 199;

    auto index = searchNearest(arr, num);
    std::cout << "The closest number is: " << arr[index]
              << " with index " << index << std::endl;
}

Live Demo