📜  array di struct - C++ (1)

📅  最后修改于: 2023-12-03 15:29:28.263000             🧑  作者: Mango

Introduction to Arrays of Structs in C++

In C++, struct is a user-defined data type that allows you to combine different data types under a single name. A struct may contain variables of different types, including other structs. Arrays of structs are particularly useful when dealing with a large amount of data items with the same properties.

Declaring an Array of Structs in C++

To declare an array of structs in C++, use the struct keyword followed by the name of the struct, followed by the name of the array. For example, to declare an array of structs named student, you would write:

struct Student {
    int id;
    string name;
    double gpa;
};

int main() {
    Student student[3];
    // ...
    return 0;
}

In this example, we create an array of 3 students. Each student has an ID, a name, and a GPA.

Initializing an Array of Structs in C++

To initialize an array of structs in C++, you can use either a designated initializer or a regular initializer. A designated initializer allows you to initialize specific struct members by name. A regular initializer initializes each member of the struct in the order they are declared.

For example, to initialize the student array of structs from the previous example, you might use:

Student student[3] = {
    {1, "John", 3.4},
    {2, "Jane", 3.8},
    {3, "Bob", 2.7}
};

Here, we use a designated initializer to specify the values for each student.

Alternatively, we could have used a regular initializer:

Student student[3] = {
    {1, "John", 3.4},
    {2, "Jane", 3.8},
    {3, "Bob", 2.7}
};

This initializes the struct members in order.

Accessing Struct Members in an Array of Structs

To access the members of a struct in an array of structs, use the dot operator followed by the member name. For example:

student[0].id = 4;
student[0].name = "Alice";
student[0].gpa = 3.2;

This code updates the values of the first student's ID, name, and GPA.

Conclusion

In this introduction to arrays of structs in C++, we learned how to declare, initialize and access the members of an array of structs. This is a powerful feature of C++ that can make it easier to manage large amounts of data.