Closed. This question needs details or clarity。它当前不接受答案。
想改善这个问题吗?添加详细信息,并通过editing this post阐明问题。
6年前关闭。
Improve this question
我有以下结构和主要功能:
我想将一个结构传递给函数搜索,然后创建一个数组指针,该指针存储某个属性的值,但存储该结构的所有数组的值。
* e指向具有所有arrays(5)的学生,因此,如果type等于1,则指针将指向结构e的每个数组的属性的所有值
我希望
问题是我找不到方法,程序中的实际结构不仅具有三个属性,实际上具有八个属性,因此如果我为每个属性做一个案例,那将浪费代码。
谢谢你的帮助。
想改善这个问题吗?添加详细信息,并通过editing this post阐明问题。
6年前关闭。
Improve this question
我有以下结构和主要功能:
struct myStruct{
string name;
int id;
int group;
};
int main(){
myStruct student[5]; // The struct student has an array of 5 elements
search(student, 1, 33); // We pass the struct student with all the 5 elements
}
我想将一个结构传递给函数搜索,然后创建一个数组指针,该指针存储某个属性的值,但存储该结构的所有数组的值。
* e指向具有所有arrays(5)的学生,因此,如果type等于1,则指针将指向结构e的每个数组的属性的所有值
void search(myStruct *e, int type, int value){
if (type == 1) int *ptr[] = e[0]->id; //An int pointer because the id is an int
if (type == 2) int *ptr[] = e[0]->group;
for (int i = 0; i < 5; i++){
if(*ptr[i] == value){
cout << e[i]->name << endl;
cout << e[i]->id << endl;
cout << e[i]->group << endl;
}
}
}
我希望
*ptr[]
指向属性的每个数组,具体取决于传入类型中传递的参数。例如:问题是我找不到方法,程序中的实际结构不仅具有三个属性,实际上具有八个属性,因此如果我为每个属性做一个案例,那将浪费代码。
谢谢你的帮助。
最佳答案
一种方法是创建“成员的指针”。注意:这不是指针数组,而是只能与该类的对象一起使用的指针。
还要注意:这是相当先进的,因此您可能想先将普通的指针弄清楚。
void search(myStruct *e, int type, int value) {
int myStruct::*ptr; // ptr is a pointer to a member variable of an object
if (type == 1) ptr = &myStruct::id;
if (type == 2) ptr = &myStruct::group;
for (int i = 0; i < 5; i++){
if (e[i].*ptr == value){ // access the value of the current object using ptr.
cout << e[i].name << endl; // Note that you had these accesses wrong.
cout << e[i].id << endl;
cout << e[i].group << endl;
}
}
}