Dynamically allocating a struct that's inside of another struct??

This is what I'm trying to do: there are many grades in a school, and each one has many students. I don't want to hard-code the amount of grades in the school (the user would specify that at compilation, hence, dynamically allocated) and I do not want to hard-code the amount of students in each grade (also specified at compilation).

This is what it would look like:

1
2
3
4
5
6
7
8
9
10
struct grades {
     int grade;
       struct students {
          int age;
          int height;
          string favorite_color;
          //etc etc etc..........
}

};


Now obviously, I can dynamically allocate grades by doing this:

1
2
int amount_of_grades = //some number......
grades *n = new grades [amount_of_grades];


and this will create as many structures "grades" as I want. HOWEVER - how do I do the same thing for the structure "students"? it's located inside the struct grades, which is why I don't know how to dynamically allocate it.

Let's suppose I even knew how many students there are in each grade (for example, 25). How would I tell the computer that there need to be 25 struct "students" in each "grade" that is created at compilation?

Any help would be appreciated.
Last edited on
Let's suppose I even knew how many students there are in each grade (for example, 25).
1
2
3
4
5
6
7
8
struct grades 
{
    struct students
    {
        //...
    };
    students array[25];
};
Or:
1
2
3
4
5
6
7
8
9
10
struct grades 
{
    struct students
    {
        //...
    };
    students* array;

    grades(int i) : array(new students[i]) {}
};
Last edited on
Grade levels don't contain students; students have a grade level. You should not nest classes like this. Instead, I'd recommend a std::multiset of students where equality is defined as having the same grade level. This will automatically sort them by grade level and allow you to pull out students based on their grade level. Alternatively you could go with a std::multimap but this creates the potential for the grade level key and the grade level in the student to go out of sync.
Last edited on
Thanks for responding! it seems to be working so far, but could you explain what line 9 in your 2nd code does? what is int i? what does the colon do? and why the {} at the end? (i'm pretty new to C++)

Thanks again!
Last edited on
Thanks! understood now.
Topic archived. No new replies allowed.