C++数组初始化方法详解
有时在程序中设置变量值比输入变量值更合适。但是,为数组的各个元素编写单独的赋值语句可能意味着大量的输入,对于大型数组而言尤其如此。
例如,来看一个程序:
#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 显示了初始化后数组的内容。
发表评论