Stewbond's advice was good and a very good starting point for a basic data structure. However, I would recommend using a class instead of struct. The only significant difference is that in a class all member variables and functions are private by default (meaning they can only be accessed from within the class functions), and in a struct all the member functions and variables are public by default. E.g.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
struct MyStruct
{
// public:
// is implied here
std::string name;
int ID;
};
class MyClass
{
// private:
// is implied here
std::string name;
int ID;
};
int main(int argc, char** argv)
{
MyStruct a_struct;
MyClass a_class;
a_struct.name = "Student Name"; // this is valid because name is public
a_class.name = "Student Name"; // this is invalid because name is private
return 0;
}
|
The reason is suggest this is you can make public functions in the class, e.g.
1 2 3 4 5 6 7 8 9 10 11 12
|
class MyClass
{
public:
void SetName(const std::string& val) { name = val; }
const std::string& GetName() const { return name; }
private:
std::string name;
int ID;
};
|
so if the name or ID variables are changed, it has to be explicitly done by invoking the "set" function. It's a bit more verbose but it's the safe practice to do as data structures get more complex because it doesn't allow for accidental reassignments that might be very difficult to locate.
also, use the STL data containers instead of C-style arrays.
1 2 3 4 5 6 7 8 9 10 11
|
// C-style array
Student students[10];
// C++ alternative
std::vector<Student> students(10);
// The benefits of this over the C-style array is you have access to member
// functions such as size() that tells you how large the data structure is
// which is very useful when constructing loops:
// for(unsigned i = 0; i < students.size(); ++i) { ... }
|
Vector is just one of many C++ data containers (vector, list, deque, map, set, multimap, ... etc.)
These containers are dynamically allocating - meaning instead of being a fixed size, you can make the container larger if you exceed 10 students in the above example. i.e.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
// ... assuming the vector of students has been fully
// populated with its initial capacity of 10 students ...
// These a better way to do this by creating non-default constructor btw
Student a_student;
a_student.SetName("John Smith");
a_student.SetID(11);
// Add another student to the data container so the size of the container
// goes from 10 to 11
students.push_back(a_student);
|