c++ - 指向结构数组属性的数组指针

标签 c++ arrays pointers struct attributes

<分区>

我有以下结构和主要功能:

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 指向学生,所有数组(5),所以如果类型等于 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[] 指向属性的每个数组,具体取决于传入的参数类型。例如:

if ( type == 1 )

ptr[0] = e[0].id;
ptr[1] = e[1].id;
ptr[2] = e[2].id;
ptr[3] = e[3].id;
ptr[4] = e[4].id;

^Notice that is just the id

if ( type == 2 )

ptr[0] = e[0].group;
ptr[1] = e[1].group;
ptr[2] = e[2].group;
ptr[3] = e[3].group;
ptr[4] = e[4].group;

^Notice that is just the group

问题是我找不到办法做到这一点,我程序中的真正结构不仅仅是三个属性,它实际上有八个,所以如果我为每一个。 感谢您的帮助。

最佳答案

一种方法是创建一个“指向成员的指针”。注意:这不是一个指针数组,而是一个只能与类的对象一起使用的指针。

另请注意:这是相当先进的,因此您可能希望先在脑海中直接获得普通指针。

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;
        }
    }
}

关于c++ - 指向结构数组属性的数组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26540218/

相关文章:

javascript - 复选框数组

c++ - 将字符串分配给指针数组

c - 用指向数组的指针填充数组

c++ - 在 C++ 中初始化 char**

c++ - VC++6错误C2059 : syntax error : 'constant'

java - 类文件错误 : "Identifier expected"

c - 返回类型为空。我的职能也需要帮助

c++ - 有效处理选项

c++ - 如何在 C++ 中跟踪我机器中的文件

python - 在 Python 的数组数组中拆分字符串的值