第 6 節

array

0瀏覽次數0訪問次數--跳出率--平均停留

array

Overview

An array is a collection that stores data elements of the same type.

Feature 1: Every ==data element in the array is of the same data type==

Feature 2: Arrays are composed of ==contiguous memory== locations.

1541748375356

one-dimensional array

一维数组定义方式

Three ways to define a one-dimensional array:

  1. 数据类型 数组名[ 数组长度 ];
  2. 数据类型 数组名[ 数组长度 ] = { 值1,值2 ...};
  3. 数据类型 数组名[ ] = { 值1,值2 ...};

Here is the translation of the provided Simplified Chinese Markdown fragment into natural American English, following all specified rules.


Example

int main() {

    //定义方式1
    //数据类型 数组名[元素个数];
    int score[10];

    //利用下标赋值
    score[0] = 100;
    score[1] = 99;
    score[2] = 85;

    //利用下标输出
    cout << score[0] << endl;
    cout << score[1] << endl;
    cout << score[2] << endl;

    //第二种定义方式
    //数据类型 数组名[元素个数] =  {值1,值2 ,值3 ...};
    //如果{}内不足10个数据,剩余数据用0补全
    int score2[10] = { 100, 90,80,70,60,50,40,30,20,10 };
    
    //逐个输出
    //cout << score2[0] << endl;
    //cout << score2[1] << endl;

    //一个一个输出太麻烦,因此可以利用循环进行输出
    for (int i = 0; i < 10; i++)
    {
        cout << score2[i] << endl;
    }

    //定义方式3
    //数据类型 数组名[] =  {值1,值2 ,值3 ...};
    int score3[] = { 100,90,80,70,60,50,40,30,20,10 };

    for (int i = 0; i < 10; i++)
    {
        cout << score3[i] << endl;
    }


    return 0;
}

Run/Observation: When executed, it will sequentially print the elements from the three arrays; each element appears on its own line in cyclic order.

Summary 1: The naming convention for arrays follows the same rules as variable naming; avoid using the same names as variables.

Summary 2: Array indexing starts from 0.

one-dimensional array name

The purpose of 1D array names:

  1. You can calculate the total memory length of an entire array.
  2. You can obtain the first address of an array in memory.

Example:

int main() {

    //数组名用途
    //1、可以获取整个数组占用内存空间大小
    int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };

    cout << "整个数组所占内存空间为: " << sizeof(arr) << endl;
    cout << "每个元素所占内存空间为: " << sizeof(arr[0]) << endl;
    cout << "数组的元素个数为: " << sizeof(arr) / sizeof(arr[0]) << endl;

    //2、可以通过数组名获取到数组首地址
    cout << "数组首地址为: " << static_cast<const void*>(arr) << endl;
    cout << "数组中第一个元素地址为: " << &arr[0] << endl;
    cout << "数组中第二个元素地址为: " << &arr[1] << endl;

    //arr = 100; 错误,数组名是常量,因此不可以赋值


    return 0;
}

Running/Observing the results: After running, the example will print variable values or addresses; address values depend on the runtime environment, so focus on observing the relative positioning and pointer changes of similar objects.

Note: The array name is a constant and cannot be assigned values.

Summary 1: Directly printing the array name allows viewing the memory address of the first element the array occupies.

Summary 2: Using sizeof on an array name retrieves the total memory size occupied by the entire array.

Practice Exercise 1: Five Little Pigs Weighing Themselves

Case Description:

An array records the weights of five little pigs, like: int arr5 = {300,350,200,400,250};

Find and print the heaviest piglet's weight.

Practice Case 2: Reversing Array Elements

Case Description: Declare an array of 5 elements and reverse its elements.

(If the original array elements are: 1,3,2,5,4; after reversal, the output is: 4,5,2,3,1);

Bubble Sort

Purpose: The most common sorting algorithm for sorting elements within arrays

  1. Compare adjacent elements. If the first element is larger than the second, swap them.
  2. Perform the same operation for each pair of adjacent elements, and after completion, find the first maximum value.
  3. Repeat the previous steps, decreasing the comparison count by one each time, until no comparisons are needed.

1541905327273

Example: Sort the array { 4,2,8,0,5,7,1,3,9 } in ascending order.

int main() {
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。

    int arr[9] = { 4,2,8,0,5,7,1,3,9 };

    for (int i = 0; i < 9 - 1; i++)
    {
        for (int j = 0; j < 9 - 1 - i; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

    for (int i = 0; i < 9; i++)
    {
        cout << arr[i] << endl;
    }
    

    // 返回 0 表示程序正常结束。
    return 0;
}

Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.

2D array

A two-dimensional array is simply a one-dimensional array with an additional dimension added.

1541905559138

Two-dimensional array definition methods

Four ways to define a two-dimensional array:

  1. 数据类型 数组名[ 行数 ][ 列数 ];
  2. 数据类型 数组名[ 行数 ][ 列数 ] = { {数据1,数据2 } ,{数据3,数据4 } };
  3. 数据类型 数组名[ 行数 ][ 列数 ] = { 数据1,数据2,数据3,数据4};
  4. 数据类型 数组名[ ][ 列数 ] = { 数据1,数据2,数据3,数据4};

Suggestion: Among the 4 definition methods above, ==the second approach is more intuitive and improves code readability==.

Example:

int main() {

    //方式1  
    //数组类型 数组名 [行数][列数]
    int arr[2][3];
    arr[0][0] = 1;
    arr[0][1] = 2;
    arr[0][2] = 3;
    arr[1][0] = 4;
    arr[1][1] = 5;
    arr[1][2] = 6;

    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

    //方式2 
    //数据类型 数组名[行数][列数] = { {数据1,数据2 } ,{数据3,数据4 } };
    int arr2[2][3] =
    {
        {1,2,3},
        {4,5,6}
    };

    //方式3
    //数据类型 数组名[行数][列数] = { 数据1,数据2 ,数据3,数据4  };
    int arr3[2][3] = { 1,2,3,4,5,6 }; 

    //方式4 
    //数据类型 数组名[][列数] = { 数据1,数据2 ,数据3,数据4  };
    int arr4[][3] = { 1,2,3,4,5,6 };
    

    return 0;
}

Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.

In summary: when defining a two-dimensional array, if the data is initialized, the number of rows can be omitted.

二维数组数组名

  • 查看二维数组所占内存空间
  • Get the first address of a two-dimensional array

Example:

int main() {

    //二维数组数组名
    int arr[2][3] =
    {
        {1,2,3},
        {4,5,6}
    };

    cout << "二维数组大小: " << sizeof(arr) << endl;
    cout << "二维数组一行大小: " << sizeof(arr[0]) << endl;
    cout << "二维数组元素大小: " << sizeof(arr[0][0]) << endl;

    cout << "二维数组行数: " << sizeof(arr) / sizeof(arr[0]) << endl;
    cout << "二维数组列数: " << sizeof(arr[0]) / sizeof(arr[0][0]) << endl;

    //地址
    cout << "二维数组首地址:" << arr << endl;
    cout << "二维数组第一行地址:" << arr[0] << endl;
    cout << "二维数组第二行地址:" << arr[1] << endl;

    cout << "二维数组第一个元素地址:" << &arr[0][0] << endl;
    cout << "二维数组第二个元素地址:" << &arr[0][1] << endl;


    return 0;
}

Running/Observing the results: After running, the example will print variable values or addresses; address values depend on the runtime environment, so focus on observing the relative positioning and pointer changes of similar objects.

Summary 1: The name of a two-dimensional array is indeed the starting address of that array.

Summary 2: When applying sizeof to a 2D array name, you can obtain the total memory space size occupied by the entire 2D array.

Two-Dimensional Array Application Cases

Exam Score Statistics:

Case description: There are three students (Zhang San, Li Si, Wang Wu), and their exam scores are as follows in the table. Please output the total scores of the three students separately.

ChineseMathematicsEnglish
Zhang San100100100
Li Si9050100
Wang Wu607080

Reference Answer:

int main() {
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。

    int scores[3][3] =
    {
        {100,100,100},
        {90,50,100},
        {60,70,80},
    };

    string names[3] = { "张三","李四","王五" };

    for (int i = 0; i < 3; i++)
    {
        int sum = 0;
        for (int j = 0; j < 3; j++)
        {
            sum += scores[i][j];
        }
        cout << names[i] << "同学总成绩为: " << sum << endl;
    }


    // 返回 0 表示程序正常结束。
    return 0;
}

Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.

音乐页