What you want to do is make a collection of student
objects.
In C++, the std::vector
class is generally the best choice for a collection type, and in your case as well.
How to use a vector
To use an std::vector
you must first #include
the <vector>
header file. Then you can declare an std::vector
object with the following syntax:
std::vector<T> name;
where T
is the type of elements you want to store in the vector
, and name
is a name for the collection. In your case, you want the type to be student
, and a good name for a collection containing students would be students
, for example:
std::vector<student> students;
Adding objects to the vector
Now you can start adding student
object to the vector
. The push_back()
function of the vector
class can be used for this, like this:
students.push_back(foo);
where foo
is a student
variable you have created earlier.
Accessing objects in the vector
Now that you have added a student
to the vector
, you can access it with the at
function:
students.at(0);
The above line will access the first object in the vector
. The at
function is also really useful if you accidentally try to access an object that's not in the vector
, for example, you try to access the second object, which we haven't added yet:
students.at(1);
Because we only have one student
stored in the vector
so far, trying to access the second student
with at
will result in an error. Which is great! Now we know we did something wrong, and the error message will probably even tell us what we did wrong.
About vector
vs raw array
A raw array like int numbers[10]
will not tell us if we accidentally try to access over the end of the array like int x = numbers[10]
. There will be no useful error messages to tell us were doing something wrong, the program will probably just silently continue execution and start behaving oddly. Which is what we as programmers don't want. Thus a vector
is a superior alternative.
Note that with a vector
you also don't have to specify a size, as with raw arrays. vector
s will automatically grow as you add new objects to it, so you don't have to worry about adding too many.