溫馨提示×

如何初始化和訪問C++ struct數(shù)組

c++
小樊
83
2024-09-10 19:25:10
欄目: 編程語言

在C++中,初始化和訪問struct數(shù)組的方法與其他類型的數(shù)組相似

#include<iostream>

// 定義一個結構體
struct Student {
    std::string name;
    int age;
};

int main() {
    // 初始化一個包含3個元素的Student結構體數(shù)組
    Student students[] = {
        {"Alice", 20},
        {"Bob", 22},
        {"Charlie", 21}
    };

    // 訪問并輸出數(shù)組中的每個元素
    for (int i = 0; i < 3; ++i) {
        std::cout << "Name: "<< students[i].name << ", Age: "<< students[i].age<< std::endl;
    }

    return 0;
}

這個示例首先定義了一個名為Student的結構體,包含兩個成員變量:nameage。然后,我們創(chuàng)建了一個包含3個Student元素的數(shù)組,并使用花括號進行初始化。接下來,我們使用for循環(huán)遍歷數(shù)組并訪問每個元素的成員變量,將它們輸出到控制臺。

0