⚙️ C++

C++17 中的二维数组:详细指南

Two-Dimensional Arrays in C++

What is a two-dimensional array and why is it needed?

Imagine a table or a chessboard. Each cell has two coordinates: row number and column number. A two-dimensional array is exactly such a table in the computer's memory. It allows you to store data that is convenient to represent as a grid: an island map, a cinema hall layout, a table of student grades, earthquake data in different regions.

In C++, a two-dimensional array is essentially an "array of arrays." First, we specify the number of rows, then the number of columns (seats in a row).

How to declare and fill a two-dimensional array?

The simplest way to declare a two-dimensional array is to specify its dimensions in square brackets:

// Array of 3 rows and 4 columns
int matrix[3][4];

You can set values immediately upon declaration:

#include <iostream>
using namespace std;

int main() {
    // 2x3 table with numbers
    int table[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };
    
    // Output the element from the first row, second column
    cout << table[0][1]; // Outputs 2
    return 0;
}

How to iterate through all elements?

To work with a two-dimensional array, nested loops are used. The outer loop iterates through rows, the inner loop through columns.

#include <iostream>
using namespace std;

int main() {
    int rows = 2, cols = 3;
    int arr[2][3] = {{10, 20, 30}, {40, 50, 60}};
    
    for (int i = 0; i < rows; i++) {      // i — row number
        for (int j = 0; j < cols; j++) {  // j — column number
            cout << arr[i][j] << " ";
        }
        cout << endl; // Move to a new line
    }
    return 0;
}

Output:

10 20 30
40 50 60

Inputting data from the keyboard

Often an array needs to be filled from the keyboard. First, we input the dimensions, then each element in a loop.

#include <iostream>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m; // Input the number of rows and columns
    
    int data[n][m]; // This works if n and m are known (works in C++17)
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> data[i][j];
        }
    }
    
    // Output everything we entered
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << data[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Example input:

2 3
1 2 3
4 5 6

Output:

1 2 3
4 5 6

Analysis of typical problems

Problem "Cozy Cinema Hall"

We need to create a hall layout. Let there be 3 rows with 4 seats each. A free seat is denoted by 'O', an occupied one by 'X'.

#include <iostream>
using namespace std;

int main() {
    char hall[3][4] = {
        {'O', 'O', 'X', 'O'},
        {'X', 'O', 'O', 'X'},
        {'O', 'X', 'O', 'O'}
    };
    
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            cout << hall[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Problem "Earthquake Data"

A 2x2 array with magnitudes. Fill it from the keyboard and find the average.

#include <iostream>
using namespace std;

int main() {
    double quakes[2][2];
    
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            cin >> quakes[i][j];
        }
    }
    
    double sum = 0;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            sum += quakes[i][j];
        }
    }
    
    cout << "Average magnitude: " << sum / 4;
    return 0;
}

Problem "Post Popularity"

Given: number of bloggers (rows) and posts (columns). Fill with likes and output.

#include <iostream>
using namespace std;

int main() {
    int bloggers, posts;
    cin >> bloggers >> posts;
    
    int likes[bloggers][posts];
    
    for (int i = 0; i < bloggers; i++) {
        for (int j = 0; j < posts; j++) {
            cin >> likes[i][j];
        }
    }
    
    for (int i = 0; i < bloggers; i++) {
        cout << "Blogger " << i+1 << ": ";
        for (int j = 0; j < posts; j++) {
            cout << likes[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Common beginner mistakes

  • Confusion with indices: In C++, counting starts from 0. The first row is index 0, the first column is also 0. arr[1][2] is the second row, third column.
  • Going out of array bounds: If the array is 3x4, the last valid index is [2][3]. Accessing [3][0] will cause an error.
  • Swapped loops: The outer loop should iterate over rows, the inner loop over columns. If they are swapped, the array will be traversed "by columns," which can lead to confusion.
  • Forgot nested curly braces: When initializing int a[2][3] = {1,2,3,4,5,6}; — this will work, but it's better to write {{1,2,3},{4,5,6}} for clarity.

Final example: Problem "Replacing Goods in a Warehouse"

We have a 3x4 warehouse. We need to replace all items with a quantity less than 5 with 0 (write them off).

#include <iostream>
using namespace std;

int main() {
    int warehouse[3][4] = {
        {10, 3, 7, 2},
        {1, 15, 4, 8},
        {6, 0, 9, 2}
    };
    
    // Replace small quantities
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            if (warehouse[i][j] < 5) {
                warehou