Data structures or struct
COS1511 - Introduction To Programming I · Learning C++
Data Structures or Struct
In C++, a structure (or struct) is a user-defined data type that allows you to combine different data types into a single unit. This is useful for grouping related data together. For example, if you want to store information about a student, you can create a structure that contains the student's name, age, and marks.
Defining a Structure
To define a structure, you use the struct keyword followed by the structure's name and its members. The members can be of different data types. Here is an example:
struct Student {
std::string name;
int age;
float marks;
};In this example, we have defined a structure called Student with three members: name of type std::string, age of type int, and marks of type float.
Creating Structure Variables
Once you have defined a structure, you can create variables of that type. Here is how to create a variable of the Student structure:
Student student1;You can also initialise the structure variables at the time of declaration:
Student student2 = {