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