中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

在C++中如何傳遞和返回struct數組

c++
小樊
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
保定市| 遵义县| 长宁县| 延庆县| 漠河县| 罗城| 曲周县| 且末县| 定边县| 六枝特区| 永新县| 潞城市| 常德市| 休宁县| 高陵县| 集贤县| 乐山市| 科技| 西平县| 定日县| 台州市| 宁明县| 天祝| 丹巴县| 肇源县| 沭阳县| 广丰县| 汝城县| 秭归县| 濮阳县| 扬州市| 漠河县| 库车县| 铜川市| 盐亭县| 金乡县| 阳谷县| 大兴区| 赤壁市| 怀远县| 清新县|