在C++中,可以通过以下方式传递和返回结构体数组:
- 使用指针传递结构体数组:
#include
struct Student {
std::string name;
int age;
};
void printStudents(Student* students, int size) {
for (int i = 0; i< size; ++i) {
std::cout << "Name: "<< students[i].name << ", Age: "<< students[i].age<< std::endl;
}
}
int main() {
Student students[] = {{"Alice", 20}, {"Bob", 22}, {"Charlie", 21}};
int size = sizeof(students) / sizeof(Student);
printStudents(students, size);
return 0;
}
- 使用引用传递结构体数组:
#include
struct Student {
std::string name;
int age;
};
void modifyStudents(Student* students, int size) {
for (int i = 0; i< size; ++i) {
students[i].age += 1;
}
}
int main() {
Student students[] = {{"Alice", 20}, {"Bob", 22}, {"Charlie", 21}};
int size = sizeof(students) / sizeof(Student);
modifyStudents(students, size);
for (int i = 0; i< size; ++i) {
std::cout << "Name: "<< students[i].name << ", Age: "<< students[i].age<< std::endl;
}
return 0;
}
- 使用
std::vector
传递和返回结构体数组:
#include
#include
struct Student {
std::string name;
int age;
};
std::vector createStudents() {
std::vector students = {{"Alice", 20}, {"Bob", 22}, {"Charlie", 21}};
return students;
}
void printStudents(const std::vector& students) {
for (const auto& student : students) {
std::cout << "Name: "<< student.name << ", Age: "<< student.age<< std::endl;
}
}
int main() {
std::vector students = createStudents();
printStudents(students);
return 0;
}
这里我们使用了std::vector
来存储结构体数组,并通过值传递和返回。std::vector
会自动管理内存,因此不需要手动分配和释放内存。