通过迭代器调用函数



在课堂教师中,我有一组科目。我想遍历这个集合,并在每个主题上调用一个函数,将学生添加到该主题。这是我的函数的外观。

void Faculty::addStudent(Student* n) {
    this->Students.insert(n);
    set<Subject*>::iterator it;
    for(it = this->Subjects.begin(); it != this->Subjects.end(); it++) {
        (*it)->addStudent(n);
    }
}

问题是我收到一个错误:

Unhandled exception at 0x01341c6d in University.exe: 0xC0000005: Access violation reading location 0x1000694d.

我正在使用Micorosft Visual 2010。

我是C++新手。

我可以提供任何其他必要的信息,只是不知道是哪个。如果需要什么,请告诉我。

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;
};

在大多数情况下,当数据在两个或多个类之间共享时,更好的做法是使用智能指针而不是原始数据指针。

例。首先,我们像这样包装指针:

typedef shared_ptr<Student> StudentSPtr;
typedef shared_ptr<Subject> SubjectSPtr;

在此之后,我们在整个代码中用这些指针(StudentSptr n而不是Student* n)替换原始指针。因此,您的函数可能如下所示:

void Faculty::addStudent(StudentSptr n){
  this->Students.insert(n);
  vector<SubjectSPtr>::iterator it;  //in your case vector is more proper, I think
  for(it = this->Subjects.begin(); it != this->Subjects.end(); it++){
    (*it)->addStudent(n);
    }
}

最新更新