指向struct数组属性的数组指针

时间:2014-10-24 01:41:51

标签: 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指向student,包含所有数组(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[]指向属性的每个数组,具体取决于在类型中传递的参数。例如:

  

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;

     

^请注意,这只是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;

     

^请注意,这只是小组

问题是我找不到办法做到这一点,我的程序中的真正结构不仅仅有三个属性,它实际上有八个,所以如果我做一个案例就会浪费代码每一个。 谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

一种非常低级的方法,只适用于POD结构类型,其属性属于同一类型(例如,int)并连续存储。

假设您的结构如下所示:

struct myStruct {
  string name;
  int attr1;
  int attr2;
  ...
  int attr8;
}

您可以按照以下方式编写搜索功能:

void search(myStruct *e, int type, int value) {
  int *ptr[5];
  for (int i = 0; i < 5; ++i) {
    int *base = &e[i].attr1; // treat attr1...attr8 as an int array
    ptr[i] = &base[type - 1];

    if (*ptr[i] == value) {
      cout << e[i].name << endl;
      for (int j = 0; j < 8; ++j) {
        cout << base[j] << endl;
      }
    }
  }
}

答案 1 :(得分:1)

执行此操作的一种方法是创建“指向成员的指针”。注意:这不是一个指针数组,而是一个只能用于该类对象的指针。

另请注意:这是相当先进的,因此您可能希望首先直接获得正常的指针。

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;
        }
    }
}
相关问题