c++ 在数组的不同索引处查找中的相同元素

r1wp621o  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(233)

我想做的是:我正在尝试做一个程序来搜索一个数组中的一个特定的int,这个int可能在数组中的许多索引处,我需要打印所有的索引(例如5在数组中出现了两次,所以我想输出两个索引)。这必须使用一个线性搜索算法来完成。
我做了什么:我已经写了一个程序,它可以输出数组中指定的int的索引,但是它只能输出第一次int在数组中的索引。下面是我写的源代码:

// This program performs a linear search on a character array

// Author: Y K

#include <iostream>
using namespace std;

int searchList(int[], int, int); // function prototype 

const int SIZE = 8;

int main()
{
    int nums[SIZE] = {3, 6, -19, 5, 5, 0, -2, 99};
    int found;
    int ch;

    cout << "Enter a number to search for:" << endl;
    cin >> ch;

    found = searchList(nums, SIZE, ch);

    if (found == -1)
        cout << "The number " << ch
             << " was not found in the list" << endl;
    else
        cout << "The number " << ch << " is in the " << found + 1
             << " position of the list" << endl;

    return 0;
}

//*******************************************************************
//  searchList
//
//  task:          This searches an array for a particular value
//  data in:       List of values in an array, the number of
//                 elements in the array, and the value searched for
//                 in the array
//  data returned: Position in the array of the value or -1 if value
//                 not found
//
//*******************************************************************

int searchList(int List[], int numElems, int value)
{
    for (int count = 0; count <= numElems; count++)
    {
        if (List[count] == value)
            return count;
    }

    return -1;  // if the value is not found, -1 is returned
}
oyxsuwqo

oyxsuwqo1#

您可以通过迭代调用searchList并在每次返回有效索引时将数组的剩余部分传递给它来完成此操作。
我将执行搜索的代码移到了另一个函数中,这样更容易多次调用。如果你只需要搜索一次,你可以将它移回main中。

#include <iostream>

int searchList(int[], int, int);

const int SIZE = 8;

void test(int *nums, int numElems, int value)
{
    bool found = false;
    int lastPos = 0;
    int index;
    while ((index = searchList(nums + lastPos, numElems - lastPos, value)) != -1)
    {
        std::cout << "found " << value << " @ " << lastPos + index + 1 << "\n";
        lastPos += index + 1;
        found = true;
    }

    if (!found)
    {
        std::cout << value << " not found.\n";
    }
}

int main()
{
    int nums[SIZE] = {3, 6, -19, 5, 5, 0, -2, 99};
    for (int value : {3, 6, -19, 5, 0, -2, 99})
    {
        test(nums, SIZE, value);
    }
    test(nums, SIZE, 1);

    return 0;
}

int searchList(int List[], int numElems, int value)
{
    for (int count = 0; count < numElems; count++)
    {
        if (List[count] == value)
            return count;
    }

    return -1;
}

Demo@CompilerExplorer
输出量:

found 3 @ 1
found 6 @ 2
found -19 @ 3
found 5 @ 4
found 5 @ 5
found 0 @ 6
found -2 @ 7
found 99 @ 8
1 not found.

相关问题