如何将结构体数组的单个成员数组传递给函数以执行线性搜索
How to pass a single member array of an array of structs to function to perform linear search
我正试图对具有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);
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- 在数组函数指针中调用void
- 数组函数似乎没有找到最大值
- 使用数组函数和循环求解伪元编码|C
- 在头文件中的函数原型中获取指针数组:函数声明为 void
- 数组函数错误输出
- 读取文件,然后创建数组函数C++
- 指针数组函数参数-奇怪的行为
- 二维数组 - 函数
- "return"没有从数组函数返回正确的值
- 数组函数问题
- 数组函数的大小返回 int 的大小而不是数组
- 从数组函数中删除元素
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- 追加/打印/插入数组c++函数问题
- 如何将数组函数转换为指针函数
- 多维数组函数输出垃圾
- C++:数组函数的递归最大值