Home  >  Article  >  Backend Development  >  How to initialize a c++ array

How to initialize a c++ array

青灯夜游
青灯夜游Original
2021-10-15 14:09:2425043browse

c Method to initialize an array: 1. Define the array first and then assign a value to the array. The syntax is "data type array name [length]; array name [subscript] = value;"; 2. Initialize the array when defining the array. , syntax "data type array name [length] = [value list]".

How to initialize a c++ array

The operating environment of this tutorial: Windows 7 system, C 17 version, Dell G3 computer.

Sometimes it is more appropriate to set the variable value in the program than to enter the variable value. However, writing separate assignment statements for each element of the array can mean a lot of typing, especially for large arrays.

For example, consider a program:

#include 
#include 
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;
}

Program output:

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.

Fortunately, there is an option. C allows initializing arrays when they are defined. By using an initializer list, you can easily initialize all elements of an array when you create it. The following statement defines the days array and initializes it with the same values ​​established by the set of assignment statements in the previous program:

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

The values ​​are stored in the array elements in the order in which they appear in the list (the first The value 31 is stored in days[0], the second value 28 is stored in days[1], etc.). The following figure shows the contents of the array after initialization.

How to initialize a c++ array

The following program is a modified version of the above program. It initializes the days array when it is created, rather than using a separate assignment statement. Note that the initialization list is spread across multiple lines. The program also adds an array of string objects to hold the month names:

#include 
#include 
#include 
using namespace std;
int main()
{
    const int NUM_MONTHS = 12;
    string name[NUM_MONTHS]={ "January", "February", "March", "April", "May" , "June", "July", "August", "September", "october", "November", "December"};
    int days[NUM_MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    for (int month = 0; month < NUM_MONTHS; month++)
    {
        cout << setw(9) << left << name[month] << " has ";
        cout << days [month] << " days. \n";
    }
    return 0;
}

Program output:

January   has 31 days.
February  has 28 days.
March     has 31 days.
April     has 30 days.
May       has 31 days.
June      has 30 days.
July      has 31 days.
August    has 31 days.
September has 30 days.
october   has 31 days.
November  has 30 days.
December  has 31 days.

So far, it has been demonstrated how to fill the array with numerical values ​​and then display all the values . However, sometimes more functionality may be needed, such as retrieving a specific value from an array. The following program is a variation of the above program that displays the number of days in a month selected by the user.

#include 
#include 
#include 
using namespace std;
int main()
{
    const int NUM_MONTHS = 12;
    int choice;
    string name[NUM_MONTHS]={ "January", "February", "March", "April", "May" , "June", "July", "August", "September", "october", "November", "December"};
    int days[NUM_MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    cout << "This program will tell you how many days are "<< "in any month.\n\n";
    // Display the months
    for (int month = 1; month <= NUM_MONTHS; month++)
        cout << setw (2) << month << " " << name [month-1] << endl;
    cout << "\nEnter the number of the month you want: ";
    cin >> choice;
    // Use the choice the user entered to get the name of
    // the month and its number of days from the arrays.
    cout << "The month of " << name [choice-1] << " has " << days[choice-1] << " days.\n";
    return 0;
}

The program output is:

This program will tell you how many days are in any month.

1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 october
11 November
12 December

Enter the number of the month you want: 4
The month of April has 30 days.

Start from array element 1

There is a lot of logic in the real world When building a model for things starting with 1, many teachers will prefer that students not use element 0, but instead start storing actual data from element 1. The number of months in the year is a good example. In this case, you can declare the name and days arrays to have 13 elements each and initialize them as follows:

string name[NUM_MONTHS+1]={" ", "January", "February", "March", "April", "May" , "June", "July", "August", "September", "october", "November", "December"};
int days[NUM_MONTHS+1] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

Note that array element 0 is not used. It's just a virtual value. This will store the name of January in name[1], the name of February in name[2], and so on. Likewise, the number of days in January will be stored in the days[1] element, the number of days in February in the days[2] element, and so on.

If you use the above method to define and initialize the array, the loop should be rewritten in the following form. It will display the contents of array elements 1~12 instead of elements 0~11 like before.

for (int month = 1; month <= NUM_MONTHS; month++)
{
    cout << setw(9) << left << name[month] << " has ";
    cout << days[month] << " days.\n";
}

If the actual data is stored starting with element 1, then there is no need to add 1 to the array subscript to locate specific data. The following is a modification of the statement that lists the number and name of each month:

for (int month = 1; month <= NUM_MONTHS; month++)
    cout << setw (2) << month << " " << name [month] << endl;

The code that displays the number of days in the month selected by the user should be modified as follows.

cout << "The month of " << name[choice] << " has "<< days [choice] << " days . \n";

Partial initialization of array

When an array is initialized, C does not have to get the value of each element, it can also just initialize it Part of the array, as shown below:

int numbers[7] = {1, 2, 4, 8};

This definition only initializes the first 4 elements of a 7-element array, as shown below.

How to initialize a c++ array
Figure 2

It is worth mentioning that the uninitialized elements in Figure 2 will all be set to zero. This is what happens when the numeric array is partially initialized. When an array of string objects is partially initialized, the uninitialized elements will all contain empty strings, that is, strings of length 0. This is true even if the partially initialized array is defined locally. However, if a local array is completely uninitialized, its elements will contain "garbage", just like other local variables.

The following program shows the contents of the numbers array after partial initialization:

#include 
using namespace std;
int main ()
{
    const int SIZE = 7;
    int numbers[SIZE] = {1, 2, 4, 8}; // Initialize the first 4 elements
    cout << "Here are the contents of the array: \n";
    for (int index = 0; index < SIZE; index++)
    cout << numbers [index] << " ";
    cout << endl;
    return 0;
}

Program output:

Here are the contents of the array:
1 2 4 8 0 0 0

Although the value of the array initialization list can be larger than the elements of the array Fewer, but no more values ​​than array elements are allowed. The following statement is illegal because the numbers array can only contain 7 values, but the initialization list contains 8 values.

int numbers [7] = {1, 2, 4, 8, 3, 5, 7, 9};    //不合法

Also, if an element is left uninitialized, all elements after that element should be left uninitialized. C does not provide a way to skip elements in an initialization list. Here is another illegal example:

int numbers [7] = {1, , 4, , 3, 5, 7};    // 不合法

Implicit array size

可以通过提供一个包含每个元素值的初始化列表来定义一个数组而不指定它的大小。C++ 会计算初始化列表中的项目数,并为数组提供相应数量的元素。例如,以下定义创建 了一个包含5个元素的数组:

double ratings [] = {1.0,1.5,2.0,2.5,3.0};

注意,如果省略大小声明符,则必须指定一个初始化列表。否则,C++ 不知道该数组有多大。

初始化变量的新方法

到目前为止,已经介绍过的定义和初始化常规变量的方法是使用赋值语句,示例如下:

int value = 5;

但是,我们已经学习过使用函数、数组以及类,所以现在是时候来介绍另外两种在定义变量的同时即进行初始化的方法。

第一种新方法是使用函数符号初始化变量。它看起来就像是给一个函数传递参数。如果您已经掌握了类的内容,那么就会注意到,它也很像是在创建类对象时给一个构造函数传递值。以下是使用函数符号定义变量 value 并初始化其值为 5 的示例语句:

int value (5);

第二种初始化变量的新方法是 C++ 11 中新引入的,使用大括号表示法。它看起来就像是刚刚上面所看到的初始化数组的方法,但是其中有两点区别:

  • 因为常规变量只能一次保存一个值,所以通过这种方法初始化变量时,大括号中只有一个值;

  • 和数组初始化列表不一样,通过这种方法初始化变量时,在大括号前面没有赋值运算符(=)。

以下是使用大括号表示法定义变量 value 并初始化其值为5的示例语句。

int value{5}; //该语句仅在C++ 11或更高版本中合法

绝大多数程序员会继续使用赋值运算符来初始化常规变量,本书也将如此,但是,大括号表示法提供了一项优点,它会检查用来初始化变量的值,并确保匹配变量的数据类型。例如,假设 doubleVal 是一个 double 类型变量,存储在其中的值为 6.2。则使用赋值运算符时,可以编写以下两种形式的语句之一:

int valuel = 4.9;    //该语句将给valuel赋值为。4
int vaule2 = doubleVal;    // 该语句将给 value2 赋值为 6

在这两种情况下,值的小数点部分都会被先截断,然后才赋值给被定义的变量。这虽然可能会导致一些问题,但 C++ 编译器是允许的,它也会提出警告,但却仍然能生成可执行文件,并且可以运行。不过,如果在这里使用的是大括号表示法,则编译器会指出这些语句产生了一个错误,并且不会生成可执行文件。必须先修复该错误,然后重新编译项目才能运行该程序。

相关推荐:《C++视频教程

The above is the detailed content of How to initialize a c++ array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn