删除后访问迭代器导致崩溃

Accessing Iterator After Deletion Causes Crash

所以我习惯了用 C# 编码,并且在相当长的一段时间后才开始再次使用 C++。本质上,我想做的是创建一个程序,在课程中包含具有 ID 的学生列表。

我有这段代码,基本上可以打印出课程中所有可用的学生。

auto allCourses = WSUCourse::getAllCourses();
   std::for_each(
       allCourses.begin(),
       allCourses.end(),
       GetCoursePrinter());

GetCoursePrinter()在构造函数中调用了这段代码

struct GetCoursePrinter
{
   void operator () (
      MyCourse *coursePtr
   )
   {
      std::cout << coursePtr->getIdentifier() <<
         ": " <<
         coursePtr->getTitle() <<
         std::endl;
   }
};

我的问题是在我像这样删除注册后

MyEnrollment *enrollmentPtr = MyEnrollment::findEnrollment(
   MyStudent::getStudentWithUniqueID(1000002),
   MyCourse::getCourseWithIdentifier("CS 2800")
);
delete enrollmentPtr;

然后尝试使用 GetCoursePrinter 打印它,但它崩溃了。我相信这是因为它试图访问不存在的东西。我想知道是否有办法调用这样的东西

if (allCourses.current() != null)
{
    GetCoursePrinter();
}
else
{
    //do nothing
}

当你打电话时:

delete enrollmentPtr;

您需要在环境中删除此项。