C++ 将类似的对象添加到 std::list 但只想要一个带有累积数据的输出

问题描述 投票:0回答:1

这可能有一个非常简单的修复方法,但我一生都看不到它。我有两个输入文件,一个包含课程,另一个包含学生。对于学生来说,它解析数据并将对象添加到列表中。我试图得到它,以便当我从列表中输出具有类似数据的学生对象(例如:Doe,John,1233485,ART Doe,John,1233485,MATH)时,它不会输出每个对象,但是具有累积数据的一个对象。 (我不知道我是否在解释最好的抱歉-)

// Parse student data
while (getline(fileStudent, studentLine)) {

    istringstream iss(studentLine);
    string lastName, firstName, SID, courseList;

    // Parse the CSV line
    if (getline(iss, lastName, ',') && getline(iss, firstName, ',') &&
        getline(iss, SID, ',') && getline(iss, courseList)) {

        // Calculate total credit hours for the student
        int totalCreditHours = 0;

        // Iterate over the courses the student has requested
        istringstream courseStream(courseList);
        string courseName;

        while (getline(courseStream, courseName, ',')) {

            // Look up the course
            auto it = courses.find(Course(courseName, 0, 0, 0));

            if (it != courses.end()) {

                // Increment enrollment count for the course
                it->incrementEnrolled();

                // Add the student to the course roster
                Course& course = const_cast<Course&>(*it); // Remove const
                course.enrollStudent(SID);

                // Update total credit hours
                totalCreditHours += it->getCreditHours();
            }
        }

        // Create the student object and add it to the list
        Student student(lastName, firstName, SID, courseList, totalCreditHours);
        students.push_back(student);
    }
}
fileStudent.close();

我已经多次尝试更改我的代码来解决这个问题。无济于事,我的程序仍然输出所有类似的对象,而不是添加任何东西在一起。

c++ output stdlist
1个回答
0
投票

我同意一个评论,你肯定需要至少分享一下 Course 是如何定义的。目前我只能猜测,我想说我在 find 方法中看到了潜在的问题。我猜这是一个 std::set 或类似的东西?如果您通过创建新的 Course 对象作为搜索参数来搜索课程,则它可能只会找到所有计数器均为 0 的课程。由于您后来修改了找到的 Course 对象,因此将不再找到它,因为它与 Course(name, 0,0,0) 对象不同(我假设它类似于 Course(name, 1,0,0 )。 这只是一个猜测,需要共享更多代码以获得更好的答案。

© www.soinside.com 2019 - 2024. All rights reserved.