对带有for循环的map迭代器可能存在的误解



非常具体的问题(我是一个新手,所以提前道歉):

我正在努力完成大学面向对象c++课程的期末项目。我正在创建一个学生数据库来存储学生的考试成绩。我的设置有大量的自定义类,但所有的工作都很完美(或者至少做我想做的事)。

项目设置如下:

我有一个所有"课程"的"主"地图,所有的东西都指向它(所以如果一个以上的学生上这门课,这门课就不会重复)。

"学生"是指向"课程"的指针和对应的双精度"结果"的向量,我有一个系统中所有学生的主地图。

一个"学位"是由两个指针向量组成的类,一个指向该学位提供的课程,另一个指向该学位的学生。当创建学位时,它会搜索两个主地图。如果课程id中的前x个字母与学位前缀匹配,则添加该课程。如果学生的科目与课程名称匹配,则添加该学生。

我的问题是:

因为我有一些选项手动输入课程和学生从CSV文件初始设置后,我已经写了一个函数来更新我的学位,如果一个课程/结果被添加,应该包括在学位(见下文)。然而,这段代码不可避免地导致第一个课程和学生在第一次调用这个函数时被重新添加(即重复)到第一次。如果再次调用该函数,则不会重复此问题。我完全不知道为什么。花了大量的时间和语句之后,我还是没有解决这个问题。我错过了什么明显的第一次运行吗?我可能设置错了循环(我不太熟悉地图)。尽管叫我白痴吧!

正如我上面所说的,程序的其余部分都很简单,如果没有这个奇怪的问题,程序就很好。问题似乎也不是来自我的打印函数。

提前感谢您的宝贵时间。

//upgrade degrees function: used whenever new courses or students could be created by the user. It ticks through all stored degrees and scans cd and sd. If it finds an unstored course or student that should be stored, they are added.
void degree_database::update_degrees(course_database &cd, student_database &sd) {
    cout << "updating degrees..." << endl;
    bool found = false;
    vector<degree>::iterator current;
    for (current = start; current < end; ++current) {
            //scan course list
        map<string, course>::iterator x;
        for (x = cd.get_start(); x != cd.get_end(); ++x) {
            if (x->first.substr(0,3) == current->get_prefix().substr(0,3) || current->get_prefix() == "ALL") {
                //check to see if course is already stored
                vector<course*>::iterator a;
                for (a = current->get_c_start(); a < current->get_c_end(); ++a) {
                    if (*a == &(x->second)) {
                        found = true;
                        break;
                    }
                }
                //if found == true, then while loop broke early (i.e. the course was already stored).
                if (found == false) current->add_course(x->second);
                found = false;
            }
        }
        //scan student list
        found = false;
        map<string, student>::iterator y;
        for (y = sd.get_start(); y != sd.get_end(); ++y) {
            if (y->second.get_subject() == current->get_name() || current->get_name() == "All") {
                //check to see if course is already stored
                vector<student*>::iterator b;
                for (b = current->get_s_start(); b < current->get_s_end(); ++b) {
                    if (*b == &(y->second)) {
                        found = true;
                        break;
                    }
                }
                //if found == true, then while loop broke early (i.e. the student was already stored).
                if (found == false) current->add_student(y->second);
                found = false;
            }
        }
    }
    cout << "done." << endl; 
}

按值将course存储在课程列表中,然后使用指针指向该对象进行比较。显然,应该在映射中存储指针。我认为(*a == &(x->second))在第一次运行时失败,从课程地图中指向对象的指针被添加到degree对象中。在第二次运行中,(*a == &(x->second))成功了,看起来一切正常。student map.

最新更新