lxg

导航

 
class StudentManager {
public:
    int addStudent(string_view name, int age, double score) { // string_view (C++17)
        int id = studentIdCounter++;
        m_students[id] = StudentInfo{ id, string(name), age, score };
        return id;
    }

    // 使用 std::optional 返回可能不存在的学生 (C++17)
    [[nodiscard]] optional<StudentInfo> findStudent(int id) const {
        auto it = m_students.find(id);
        if (it != m_students.end()) {
            return it->second;
        }
        return nullopt;
    }

    // 修改学生信息 - 使用 optional 参数实现部分更新 (C++17)
    [[nodiscard]] bool updateStudent(int id, 
        optional<string_view> name = nullopt,
        optional<int> age = nullopt, 
        optional<double> score = nullopt) 
    {
        if (auto it = m_students.find(id); it != m_students.end()) {  // if 初始化语句
            auto& [studentId, studentName, studentAge, studentScore] = it->second;  // 结构化绑定
            
            // 使用 optional::value_or 的替代方案,只在有值时更新
            if (name) studentName = string(*name);
            if (age) studentAge = *age;
            if (score) studentScore = *score;
            
            return true;
        }
        return false;
    }

    // 使用 variant 返回修改结果或错误 (C++17)
    variant<StudentInfo, string> updateStudentOrError(int id,
        optional<string_view> name = nullopt,
        optional<int> age = nullopt,
        optional<double> score = nullopt)
    {
        if (updateStudent(id, name, age, score)) {
            return *findStudent(id);
        }
        return string("Update failed: student not found with ID ") + to_string(id);
    }

    // 使用 std::variant 返回结果或错误信息 (C++17)
    variant<StudentInfo, string> getStudentOrError(int id) const {
        if (auto student=  findStudent(id); student)
        {
            return*student;
        }
        return string("Student not found: ") + to_string(id);
    }

void testStudentManager() {
using namespace School::Student;
StudentManager manager;

int id1 = manager.addStudent("Alice", 20, 85.5);
int id2 = manager.addStudent("Bob", 21, 92.5);
int id3 = manager.addStudent("Charlie", 19, 78.0);

cout << "=== 所有学生 ===" << endl;
manager.printAllStudents();

// 测试修改功能
cout << "\n=== 修改学生信息 ===" << endl;
// 只修改成绩,其他保持不变 (使用 optional 实现部分更新)
if (manager.updateStudent(id1, nullopt, nullopt, 95.0)) {
    cout << "成绩修改成功!" << endl;
}
// 修改姓名和年龄
manager.updateStudent(id2, "Bobby", 22);

// 使用 variant 版本修改并获取结果
auto updateResult = manager.updateStudentOrError(id3, "Charles", 20, 88.5);
visit([](auto&& arg) {
    using T = decay_t<decltype(arg)>;
    if constexpr (is_same_v<T, StudentInfo>) {
        cout << "修改成功: " << arg.name << ", 新成绩: " << arg.score << endl;
    } else {
        cout << "错误: " << arg << endl;
    }
}, updateResult);

cout << "\n=== 修改后的学生列表 ===" << endl;
manager.printAllStudents();
posted on 2026-01-30 13:58  lxg_7105  阅读(1)  评论(0)    收藏  举报