亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

在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
平安县| 阿城市| 宜宾市| 澄迈县| 松溪县| 临海市| 滦平县| 龙游县| 江都市| 长子县| 凤山县| 乐清市| 墨玉县| 远安县| 梅河口市| 罗定市| 视频| 钟祥市| 汶川县| 东乌珠穆沁旗| 通海县| 涿鹿县| 浙江省| 揭阳市| 正安县| 马尔康县| 三江| 峨山| 万全县| 千阳县| 合阳县| 江孜县| 汝城县| 理塘县| 遂川县| 伊宁县| 武清区| 镇雄县| 瑞安市| 安康市| 舟山市|