在C++项目中,合理使用struct数组可以帮助你更好地组织和管理数据。以下是一些建议:
struct Student {
std::string name;
int age;
float score;
};
const int MAX_STUDENTS = 100;
Student students[MAX_STUDENTS];
for (int i = 0; i < MAX_STUDENTS; ++i) {
students[i].name = "";
students[i].age = 0;
students[i].score = 0.0;
}
students[0].name = "Alice";
students[0].age = 20;
students[0].score = 90.5;
students[1].name = "Bob";
students[1].age = 22;
students[1].score = 85.0;
for (int i = 0; i < MAX_STUDENTS; ++i) {
std::cout << "Name: "<< students[i].name << ", Age: "<< students[i].age << ", Score: "<< students[i].score<< std::endl;
}
Student findBestStudent(Student students[], int size) {
Student bestStudent = students[0];
for (int i = 1; i< size; ++i) {
if (students[i].score > bestStudent.score) {
bestStudent = students[i];
}
}
return bestStudent;
}
int numStudents = 100; // 可以根据需要更改
Student* students = new Student[numStudents];
记住在使用完动态分配的内存后,要释放它以避免内存泄漏:
delete[] students;
通过遵循这些建议,你可以在C++项目中合理地使用struct数组来组织和管理数据。