Structs and vectors are similar in that they allow us to store multiple values in a package with a single name. But there are some important differences:
Every member of a struct can be of any type, while all members of a vector must be of the same type.
You can use a loop to traverse a vector or a variable to easily store an index. There is no equivalent way to loop through the members of a struct or specify one with a variable.
There are times where we could use either a vector or a struct to store a collection of data. We could store a mathematical point as a struct with two members, x and y, or we could store it as a vector with two elements. But usually, one of the two is a better choice. Here are some guidelines to help you decide which to use:
If all the items are a different type, you need a struct.
So what if you need the strengths of booth? You can combine the two by using a vector inside of a struct, by making a vector of structs, or even by doing both at once.
Say we want to store students who have names and a list of exam scores. We would like to be able to loop through their scores to do things like calculate an average. We also need to be able to add scores. We could represent those scores as a vector of doubles within a Student struct:
Now a student is defined as something that has a name and an exams. The exams is a list (vector) of values. The memory diagram for a particular student would look something like this:
// Print the first exam score
cout << student1.exams.at(0) << endl;
// Print the number of exams
cout << student1.exams.size() << endl;
// Add a new score
student1.exams.push_back(100.0);
Elements have indexes, not names. In some situations, 0, 1, 2, ... might be considered meaningful, but you canβt assign other names to identify the elements.