c++

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

小樊
117
2024-09-10 19:36:29
栏目: 编程语言

在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会自动管理内存,因此不需要手动分配和释放内存。

0
看了该问题的人还看了