如何将C++ 4个vector的学生项目改写为Student类单vector版本
单vector+Student类改写思路提示
核心逻辑非常直白:你之前用4个vector存储数据时,是靠相同下标对齐同一个学生的不同属性,现在的vector<Student>只是把同一个学生的所有属性打包成一个Student类实例,作为vector的单个元素存储,本质上下标对齐的逻辑完全没变,只是把分散存储的属性收拢到了类对象内部。
具体改写按下面步骤走就行:
- 保留你之前写好的文件读取逻辑,不需要大改。原来每读到一组完整的学生数据(名字、姓氏、学号、分数),你是分别往4个独立vector的尾部push对应值;现在改成每读到一组完整数据,先创建一个临时的空
Student对象。 - 调用这个临时Student对象对外提供的public setter方法,把刚读到的字段逐个写入对象:读到学号就调
setId(读到的学号字符串),读到姓名、姓氏就对应给对象内的firstName、lastName赋值(按照头文件给的setName接口约定实现对应逻辑即可),读到分数就调setPoints(读到的分数值),读到考试权重参数就调setExamWeights()传入三个权重值。 - 等临时Student对象的所有属性都赋值完成,直接把这个整个对象
push_back到你定义的唯一的vector<Student>类型容器里即可,不需要再往4个独立vector里存值。
新旧逻辑对应关系参考:
旧版本:4个vector的第i个元素拼接起来,才是第i个学生的完整信息
新版本:vector<Student>的第i个元素本身就存储了第i个学生的全部信息,需要取对应属性时,直接调用该位置对象的getter方法即可——比如取第i个学生的学号写stu_vec[i].getId(),取名字写stu_vec[i].getFirstName(),和你之前按下标从4个vector取值的逻辑完全对应,只是把name[i]这类写法换成了调用对象的get方法。
老师提供的头文件参考:
#ifndef student_h #define student_h #include <iostream> #include <string> #include <vector> using namespace std; class Student{ public: Student(); void setId(string); string getId() const; void setName(string); string getFirstName() const; string getLastName() const; void setPoints(double); double getPoints() const; void display(vector<Student>&, int); // Exam Functions void setExamWeights(double, double, double); double getGrade(string, double) const; private: string firstName; // name of the student (include middle name if exists) string lastName; // lastname of the student string ID; // identity number of the student double points; double midtermWeight; double finalWeight; double hwWeight; }; #endif
额外两个实现小提示:
- 类成员函数的实现没有特殊技巧,比如
setId方法的逻辑就是把传入的参数赋值给类内部的私有成员ID,getter方法直接返回对应私有成员的值即可,和你之前直接操作普通变量、vector元素的逻辑完全一致,只是现在操作的是类对象的内部成员。 - 原来你遍历4个vector做成绩计算、信息输出的逻辑,现在改成遍历这一个
vector<Student>就行,每遍历到一个元素就是一个完整的学生对象,直接调用它的getGrade()、display()方法就能完成原有功能,反而不需要再维护4个vector的下标同步,能减少下标不匹配导致的bug。
内容的提问来源于stack exchange,提问作者Oprasis
相关产品推荐
相关产品推荐

