C ++中的嵌套结构函数

时间:2018-07-08 18:52:34

标签: c++ function nested structure dynamic-memory-allocation

我在完成一项任务时遇到了麻烦(或者我想得太多了吗?) 我需要创建

  1. 一个采用整数参数表示学生和测试数量的函数。
  2. 为每个学生分配数组和每个学生的考试分数。
  3. 返回一个指向Student结构数组的指针。此功能没有显示输出。

    int main()
    {
        int studentNum;
        int testNum;
    
        cout << "How many students are there?\n";
        cin >> studentNum;
        cout << "How many tests are there?";
        cin >> testNum;
    
        system("pause");
        return 0;
    }
    

我的功能

GradeBook *initArrays(int s, int t)
{
    GradeBook *ptr;

// Allocate the array of Student structures.
ptr = new GradeBook[s];

// Allocate an array of ints (to hold test scores)
// for each element of the array of Student structures.
for (int count = 0; count < s; count++)
{
    ptr[count].tests = new int[t];
}

// Return a pointer to the array of structures.
return ptr;

}

编辑:我已经编辑了函数,可以对此发表一些意见吗?

2 个答案:

答案 0 :(得分:1)

如果使用c ++编写,请使用类。如果我理解正确,您应该创建一个结构来保存学生ID,姓名或其他内容以及相应的成绩吗?

类似:

class Test{
public:
    int id;
    int grade;
    Test(int id, int grade){
        this->id = id;
        this->grade = grade;
    }
};

class Student{
public:
    int id;
    std::string name;
    std::vector<Test> tests;
    Student(int id, std::string name)
    {
        this->id = id;
        this->name = name;
    }
};

int main(){
    vector<Student> students;
    int studentnum;
    for (int i = 0; i < studentnum; i++){
        students.push_back(Student(i, "name"));
        //insert all tests of the student by calling students[i].tests.push_back(Test(id, grade))
    }
}

通过这种方式,您不必分配内存,而您很容易忽略释放空间。

编辑: 这是非常基础的,不是复杂的解决方案,因为这些类的属性都是公共的。

编辑2:

    typedef struct Test{
    int id;
    int grade;
}Test;

typedef struct Student{
    int id;
    std::string name;
    Test * tests;
}Student;

int main(){
    Student * students;
    int studentnum;
    students = (Student*)malloc(sizeof(Student)*studentnum);
    for (int i = 0; i < studentnum; i++){
        students[i]->id = id;
        students[i]->name = "name";
        student[i]->tests = (Test*)malloc(sizeof(Test)*numberofgradesofthatstudent);
        for (int j = 0; j < numberofgradesofthatstudent; j++)
        {
            students[i]->tests[j]->id = testid;
            students[i]->tests[j]->grade = grade;
        }
    }
}

这是示意图! new和malloc在堆上保留内存,完成后不要忘记释放所有内容。

答案 1 :(得分:-1)

如前所述,请小心使用方括号{}来分隔块。

第二,语法:

array[studIndex].Tests

假定值array [studIndex](此处为整数)具有名为Tests的成员值。但是在这种情况下,事实并非如此。

请考虑一下您的问题:您需要在静态数组中存储彼此“连接”的两个值。我的看法是,您应该尝试使用二维数组:

int 2dArray[nbStudents][nbTests];

如果您不想打扰二维数组,也可以尝试

int 2dArray[nbStudents * nbTests];

但是为了方便起见,通常最好使用2d数组。

此外,考虑在函数的for循环之前声明数组。 然后像您那样连接两个for循环,让您考虑其余的...