c++ - Calling functions through Iterator? -
in class faculty, have set of subjects. want go through set , on each subject call function adds student subject. here how function looks.
void faculty::addstudent(student* n) { this->students.insert(n); set<subject*>::iterator it; for(it = this->subjects.begin(); != this->subjects.end(); it++) { (*it)->addstudent(n); } }
the problem error:
unhandled exception @ 0x01341c6d in university.exe: 0xc0000005: access violation reading location 0x1000694d.
i using micorosft visual 2010.
i new c++.
i can provide other necessary information, don't know which. please tell me if needed.
class student: public human { friend class university; friend class faculty; friend class subject; public: student(string name, string surname); ~student(); void index(int n); private: int index; };
in cases, such this, better practice using smart pointers instead of raw data pointers when data shared between 2 or more classes.
example. @ first, wrap pointers this:
typedef shared_ptr<student> studentsptr; typedef shared_ptr<subject> subjectsptr;
after this, replace raw pointers these pointers (studentsptr n
instead of student* n
) in entire code. so, function may this:
void faculty::addstudent(studentsptr n){ this->students.insert(n); vector<subjectsptr>::iterator it; //in case vector more proper, think for(it = this->subjects.begin(); != this->subjects.end(); it++){ (*it)->addstudent(n); } }
Comments
Post a Comment