在C++中如何传递和返回struct数组

avatar
作者
筋斗云
阅读量:0

在C++中,可以通过以下方式传递和返回结构体数组:

  1. 使用指针传递结构体数组:
#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; } 
  1. 使用引用传递结构体数组:
#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; } 
  1. 使用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会自动管理内存,因此不需要手动分配和释放内存。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!