Home > Blockchain >  Use vector or map for input of a class of students?
Use vector or map for input of a class of students?

Time:12-09

I am writing a code for storing information from user input, with two different strings and one char. The program is supposed to take in multiple inputs until the user gives stop as a course name. All of the objects in the class are printed out with an iterator for loop when the student name given is stop.

At the start, I created a class like this:

class Student{
public:
  string Name;
  string Course;
  char Grade;
};

Can a vector be used for all of the input?

I have tried using a map, but I am uncertain of the use.

CodePudding user response:

If you need a list-of-students, use a data structure suitable for a list-of-students. A vector is one, and generally the one you should reach for if you don't have good reasons not to. You mention a map -- that associates a key with a value, so it's useful when you have a "key" that you might want to look up later. Which is right for you -- or for your problem -- depends on what you actually want to do with the data.

You might do something like this (not complete code: you would need to fill in the includes and supporting functions):

std::vector<Student> all_students;
while(true) {
  Student one_student;
  // Function reads from an input stream, puts information in Student&
  readStudentInformation(std::cin, one_student);
  if (reasonToStop(one_student)) { break; }
  else { all_students.append(one_student); }
}

You read things one at a time, and add the valid ones into the vector-of-students. (This sample code assumes you can look up how to use a Student&, a reference-to-student, to update the one_student).

CodePudding user response:

You can use a vector, map or any other container to store the student information. You choose one depending on WHAT you are going to do with it? Specifically - HOW will you access that information?

Also, your description hints that one student may take multiple courses, each with its own grade. You class Student can't store that.

  • Related