91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

在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
独山县| 乌兰县| 城固县| 尤溪县| 乌兰察布市| 大渡口区| 阿鲁科尔沁旗| 肃宁县| 伊川县| 青河县| 莒南县| 南宁市| 雷波县| 花莲市| 中宁县| 永年县| 灵丘县| 睢宁县| 三河市| 迁安市| 盐山县| 富平县| 耒阳市| 罗田县| 河曲县| 子洲县| 武冈市| 游戏| 定日县| 襄城县| 达尔| 秭归县| 巴林左旗| 德江县| 临猗县| 桂东县| 二连浩特市| 来凤县| 志丹县| 兴海县| 喀喇沁旗|