C++陣列初始化方法詳解

2020-07-16 10:04:40
有時在程式中設定變數值比輸入變數值更合適。但是,為陣列的各個元素編寫單獨的賦值語句可能意味著大量的輸入,對於大型陣列而言尤其如此。

例如,來看一個程式:
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    const int NUM_MONTHS = 12;
    int days[NUM_MONTHS];
    days[0] = 31; // January
    days[1] = 28; // February
    days[2] = 31; // March
    days[3] = 30; // April
    days[4] = 31; // May
    days[5] = 30; // June
    days[6] = 31; // July
    days[7] = 31; // August
    days[8] = 30; // September
    days[9] = 31; // October
    days[10] = 30; // November
    days[11] = 31; // December
    for (int month = 0; month < NUM_MONTHS; month++)
    {
        cout << "Month "<< setw (2) << (month+1) << " has ";
        cout << days[month] << " days.n";
    }
    return 0;
}
程式輸出結果:

Month  1 has 31 days.
Month  2 has 28 days.
Month  3 has 31 days.
Month  4 has 30 days.
Month  5 has 31 days.
Month  6 has 30 days.
Month  7 has 31 days.
Month  8 has 31 days.
Month  9 has 30 days.
Month 10 has 31 days.
Month 11 has 30 days.
Month 12 has 31 days.

幸運的是,還有一個選擇,C++ 允許在定義陣列時初始化陣列。通過使用初始化列表,可以在建立陣列時輕鬆初始化陣列的所有元素。以下語句定義 days 陣列,並使用之前程式中賦值語句集所建立的相同值對其進行初始化:

int days [NUM_MONTHS] = {31,28,31,30,31,30,31,31,30,31,30, 31};

這些值按照它們出現在列表中的順序儲存在陣列元素中(第一個值 31 儲存在 days[0]  中,第二個值 28 儲存在 days [1] 中,等等)。圖 1 顯示了初始化後陣列的內容。

通過初始化列表賦值後的數組內容
圖 1 通過初始化列表賦值後的陣列內容