在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;
}
这些技巧可以帮助你更有效地使用结构体数组和指针。请注意,这里的代码示例仅用于说明目的,实际应用中可能需要根据具体情况进行调整。