在C++中,結構體(struct)是一種自定義的數據類型,它可以存儲不同類型的數據。當涉及到結構體數組和指針時,有一些技巧可以簡化代碼和提高效率。以下是一些建議:
struct Student {
int id;
string name;
float score;
};
Student s1;
Student students[] = {
{1, "Alice", 90},
{2, "Bob", 85},
{3, "Charlie", 92}
};
Student *pStudent = &students[0];
cout << pStudent->name<< endl; // 輸出 "Alice"
int n = sizeof(students) / sizeof(Student);
for (int i = 0; i < n; ++i) {
cout<< students[i].id << " "<< students[i].name << " "<< students[i].score<< endl;
}
for (int i = 0; i < n; ++i) {
Student *pStudent = &students[i];
cout << pStudent->id << " " << pStudent->name << " " << pStudent->score<< endl;
}
void printStudents(Student *students, int n) {
for (int i = 0; i < n; ++i) {
cout<< students[i].id << " "<< students[i].name << " "<< students[i].score<< endl;
}
}
int main() {
// ... 初始化結構體數組
printStudents(students, n);
return 0;
}
Student* findStudentById(Student *students, int n, int id) {
for (int i = 0; i < n; ++i) {
if (students[i].id == id) {
return &students[i];
}
}
return nullptr;
}
int main() {
// ... 初始化結構體數組
Student *pFound = findStudentById(students, n, 2);
if (pFound != nullptr) {
cout << pFound->name<< endl; // 輸出 "Bob"
}
return 0;
}
這些技巧可以幫助你更有效地使用結構體數組和指針。請注意,這里的代碼示例僅用于說明目的,實際應用中可能需要根據具體情況進行調整。