I am doing a homework for my Systems Programming course.
I have to implement a University simulation.
I have a Course abstract class, and child class of it ComputerScienceCourse (and a bunch of other child classes that don’t affect what I’m going to ask).
and I have a Student abstract class, and child class of it ComputerScienceStudent (and a bunch of other child classes that don’t affect what I’m going to ask).
In the ComputerScienceCourse child class there is a function:
void teach(){
for(i = all students that take this course [stored in a vector of pointers to Student objects, which is a member field of the CSCourse child class, called students]){
this->students.at(i)->study(*this);
}
}
This function calls study function for all students that have taken this class. The function is a member function of child class CSStudent
void study(Course &c){
if(this->failedclass){
c.removeStudent(this)
}
}
Now when I check the output, the loop in the teach function does not call the study function for all the students within.
For example, if I have 4 students doing this course, sometimes it would call the study function of only the first three, sometimes it calls the function for the first and the last student… varies.
What could be causing the for loop to not call ALL students study functions?!
Here’s the full code for the teach function:
for(unsigned int i=0; i<this->studentMembers.size(); i++){
this->studentMembers.at(i)->study(*this);
}
The problem seems to be that when a student fails a course, the contents of the vector get modified. Removing things from a vector while you’re iterating through its contents is tricky to get right. Seems like a more appropriate data model here would have the instructor remove students who fail, which would also make this problem much more tractable. So teach everyone, and then go through the list again to remove students who failed.