在C++中,可以通過以下方式傳遞和返回結構體數組:
#include<iostream>
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<iostream>
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<iostream>
#include<vector>
struct Student {
std::string name;
int age;
};
std::vector<Student> createStudents() {
std::vector<Student> students = {{"Alice", 20}, {"Bob", 22}, {"Charlie", 21}};
return students;
}
void printStudents(const std::vector<Student>& students) {
for (const auto& student : students) {
std::cout << "Name: "<< student.name << ", Age: "<< student.age<< std::endl;
}
}
int main() {
std::vector<Student> students = createStudents();
printStudents(students);
return 0;
}
這里我們使用了std::vector
來存儲結構體數組,并通過值傳遞和返回。std::vector
會自動管理內存,因此不需要手動分配和釋放內存。