Search code examples
c++loopsclassvectorinstance

How to store an instance of class in a vector?


I have made a class for a student with course and grade, the program keeps asking for a new student until the name given is stop. To store these instances I want to use a vector, but I didn't find any other way to store them than creating an array for the instances first and then pushing them back into the vector. Is it possible to have room for one instance and delete the values stored in Student student after use so it can be reused?

int i=0;
Student student[20];
vector<Student> students;


cout << "Name?" << endl;
getline(cin,student[i].name);
while((student[i].name) != "stop")
{
    student[i].addcoursegrade();
    students.push_back(student[i]);
    i++;
    cout << "Name?" << endl;
    getline(cin,student[i].name);
    if((student[i].name) == "stop")
        break;

};

I also use vectors inside the class to store the values for course and grade, since they are also supposed to be growing. The code for the class is here:

class Student {
public:
    string name;

void print() {
    cout << name ;

    for (int i = 0; i < course.size(); i++)
        cout << " - " << course[i] << " - " << grade[i];
    cout<<endl;
}

void addcoursegrade() {
    string coursee;
    string gradee;

    cout << "Course?" << endl;
    getline(cin, coursee);
    course.push_back(coursee);
    while (coursee != "stop") {
        cout << "Grade?" << endl;
        getline(cin, gradee);
        grade.push_back(gradee);
        cout << "Course?" << endl;
        getline(cin, coursee);
        if (coursee != "stop")
            course.push_back(coursee);
        else if(coursee == "stop")
            break;
    }
};

private:
   vector<string> course;
   vector<string> grade;
};

Solution

  • Instead of creating an array then pushing back, simply keep one instance around and reassign it:

    Student student;
    vector<Student> students;
    
    cout << "Name?" << endl;
    getline(cin,student.name);
    while((student.name) != "stop")
    {
        student.addcoursegrade();
    
        // this line copies the student in the vector
        students.push_back(student);
    
        // then, reassign the temp student to default values
        student = {};
    
        cout << "Name?" << endl;
        getline(cin,student.name);
        if((student.name) == "stop")
            break;
    };