如何在c++中传递数据结构数据数组作为函数的参数



所以我声明了这个结构data:

struct Auxiliary
{
char come_greet[100], leave_greet[100], aux_words[100];  
};
Auxiliary j[1000];

现在我需要在函数中使用这些数据但我不能将结构作为参数传递:

void search_for_val_name(struct StructName & y[] ,char name1[],char answer[], int mm)
{
for(int i=0;i<mm;i++)
{
if(strchr(answer,(*y).name1))
return (*y).name1;
}
}

我怎样才能使这个函数正常工作?

首先,这是c++,所以所有那些固定大小的数组都只是等待缓冲区溢出——对于如此大的结构体,这样做没有任何性能上的好处。

因此,我将这样开始。每当需要未知数量的字符时,就使用std::string。当需要未知数量的其他类型元素时,使用std::vector

#include <string>
#include <vector>
struct Auxiliary {
std::string come_greet, leave_greet;
std::vector<std::string> aux_words; // if this is just one word, don't call it words!
bool operator==(const Auxiliary &o) const {
return &o == this ||
o.come_greet == come_greet &&
o.leave_greet == leave_greet &&
o.aux_words == aux_words;
}
};
struct Outer {
static Auxiliary not_found;
std::vector<Auxiliary> j; // j is a terrible name - choose something with meaning!
Auxiliary &find_answer(std::string Auxiliary::*field, const std::string &answer);
};

然后,搜索是一个方法:它不需要有mm参数,因为它知道j向量的大小,它不需要提供j,因为它可以直接访问它,我们实际上可以写c++,而不是C。field参数指定Auxiliary结构的哪个成员是要搜索的,例如&Auxiliary::come_greet。还要注意使用std::string::find而不是strstrfind_answerAuxiliary返回引用,因为返回引用很便宜。它也可以返回(即Auxiliary,而不是Auxiliary&),但这将复制值,很可能是不必要的。

Auxiliary Outer::not_found;
Auxiliary& Outer::find_answer(std::string Auxiliary::*field, const std::string &answer) {
for (auto &aux : j)
if ((aux.*field).find(answer) != std::string::npos)
return aux;
return not_found;
}

如果您不需要通过返回的引用修改Auxiliary,则返回类型应该是const Auxiliary&

最后,一个演示行为的小测试:

#include <cassert>
int main() {
Outer outer;
outer.j = {
{"come0", "leave0", {"auxa_0", "auxb_0"}},
{"come1", "leave1", {"auxa_1"}}
};
assert(outer.find_answer(&Auxiliary::come_greet, "foo") == Outer::not_found);
assert(outer.find_answer(&Auxiliary::come_greet, "come0") == outer.j[0]);
assert(outer.find_answer(&Auxiliary::come_greet, "come1") == outer.j[1]);
assert(outer.find_answer(&Auxiliary::leave_greet, "leave0") == outer.j[0]);
assert(outer.find_answer(&Auxiliary::leave_greet, "leave1") == outer.j[1]);
}

完整的可编译示例结束。

由于要搜索的数组元素的数量是可变的,因此应该通过指针传递结构数组,而不是通过引用。

看起来您还希望调用者指定要在数组中搜索哪个结构字段。您可以使用指向成员的指针来实现这一点。

试试这个:

typedef char wordStr[100];
struct Auxiliary
{
wordStr come_greet, leave_greet, aux_words;
};
char* search_for_val_name(Auxiliary* y, wordStr Auxiliary::*field, char* answer, int mm)
{
for(int i = 0; i < mm; ++i)
{
if (strstr(answer, y[i].*field))
return y[i].*field;
}
return NULL;
}
Auxiliary j[1000];
...
char *found = search_for_val_name(j, &Auxiliary::aux_words, "answer", 1000);
...

最新更新