如何将结构体数组的单个成员数组传递给函数以执行线性搜索

How to pass a single member array of an array of structs to function to perform linear search

本文关键字:数组 函数 线性搜索 执行 成员 结构体 单个      更新时间:2023-10-16

我正试图对具有3个成员的结构数组的一个成员数组执行线性搜索。

我想让它只搜索门牌号,但是我搞不懂语法。

如果它只是一个单一的数组,我可以这样做,如果它只是一个结构体,我可以这样做,但因为它是一个结构体数组,我挣扎。你能帮我处理一下函数头和调用吗?

任何帮助都将非常感激。提前感谢!

#include <iostream>
using namespace std;
struct Build
{
    int number;
    string size;
    char wall_type;
};
int searchArray(const int [], int);

int main ()
{
   int result,                // Index of array that matches search
       value;                // The house number entered by user
   Build house[5] = {
                       {1, "big", 'F'},
                       {3, "small", 'D'},
                       {5, "tiny", 'A'},
                       {7, "huge", 'B'},
                       {9, "medium", 'F'}
                    };
   for (int i = 0; i < 5; i++)              // Just a test to see if the 
   {                                       // array is populated correctly
       cout << house[i].number << "  "
            << house[i].size << "  "
            << house[i].wall_type << endl << endl;
   }
   cout << "Enter the house number:  ";
   cin  >> value;
   result = searchArray(house.number, value);
   if (result == -1)
       cout << "Not found." << endl;
   else
   {
      cout << "Index number:  " << result << endl
           << "House number:  " << house[result].number << endl;
   }
   return 0;
}

/***************************************************************
 *
 *   This function searches an array of integers to find a match
 *   entered by the user.  It works great if you are just dealing
 *   with a single array but I can't figure out the syntax to 
 *   search just one member of a struct in an array of structs.  
 *   Please help!
 *
 */
int searchArray(const int list[], int value)
{
    int index = 0;
    bool found = false;
    int position = -1;
    while (index < 5 && !found)
    {
        if (list[index] == value)
        {
            found = true;
            position = index;
        }
        index++;
    }
    return position;
}

问题在于调用。你不能只传门牌号。你可以传递给搜索函数:

  • 整个构建数组(并根据构建的结构适当调整搜索功能)
  • 新的int数组(你必须创建一个)

,然后可以执行搜索。

你可以试试:

int intArray[5];
for(int iter=0; iter<5; ++iter){
    intArray[iter] = house[iter].number;
}
int result = searchArray(intArray, value);