C++学习笔记-多维数组

多维数组在C++中可以通过多种方式实现,包括静态数组、动态分配的指针数组,以及将多维数组转换为一维数组。推荐将多维数组转换为一维数组,因为在动态内存分配时更加高效,而且也更简单。

静态多维数组

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>

int main()
{
    // 静态二维数组
    int staticArray[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
    
    std::cout << "=== Static 2D Array ===" << std::endl;
    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 4; ++j)
        {
            std::cout << staticArray[i][j] << " ";
        }
        std::cout << std::endl;
    }
    
    // 静态三维数组
    int static3D[2][3][4];
    
    // 初始化三维数组
    int value = 1;
    for (int i = 0; i < 2; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            for (int k = 0; k < 4; ++k)
            {
                static3D[i][j][k] = value++;
            }
        }
    }
    
    std::cout << "\n=== Static 3D Array ===" << std::endl;
    for (int i = 0; i < 2; ++i)
    {
        std::cout << "Layer " << i << ":" << std::endl;
        for (int j = 0; j < 3; ++j)
        {
            for (int k = 0; k < 4; ++k)
            {
                std::cout << static3D[i][j][k] << " ";
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
    
    return 0;
}

动态二维数组

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

int main()
{
    const int rows = 50;
    const int cols = 50;
    
    /* 动态二维数组 */
    int** a2d = new int*[rows];
    for (int i = 0; i < rows; i++)
        a2d[i] = new int[cols];

    /* 初始化二维数组 */
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            a2d[i][j] = i * cols + j;

    /* 二维数组的访问 */
    std::cout << "=== Dynamic 2D Array Access ===" << std::endl;
    std::cout << "a2d[2][2] = " << a2d[2][2] << std::endl;
    std::cout << "(*(a2d+2))[2] = " << (*(a2d+2))[2] << std::endl;
    std::cout << "*(*(a2d+2)+2) = " << *(*(a2d+2)+2) << std::endl; // 推荐使用这种方式

    /* 释放二维数组 */
    for (int i = 0; i < rows; i++)
        delete[] a2d[i];
    delete[] a2d;
    
    std::cout << "Dynamic 2D array cleaned up" << std::endl;

    return 0;
}

一维数组模拟多维数组(推荐方法)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
#include <iostream>
#include <vector>

class Array2D
{
private:
    int* m_Data;
    int m_Rows, m_Cols;
    
public:
    Array2D(int rows, int cols) : m_Rows(rows), m_Cols(cols)
    {
        m_Data = new int[rows * cols];
    }
    
    ~Array2D()
    {
        delete[] m_Data;
    }
    
    // 禁用拷贝构造和赋值
    Array2D(const Array2D&) = delete;
    Array2D& operator=(const Array2D&) = delete;
    
    // 访问元素
    int& operator()(int row, int col)
    {
        return m_Data[row * m_Cols + col];
    }
    
    const int& operator()(int row, int col) const
    {
        return m_Data[row * m_Cols + col];
    }
    
    // 获取原始指针(用于与C API交互)
    int* GetData() { return m_Data; }
    const int* GetData() const { return m_Data; }
    
    // 获取维度
    int GetRows() const { return m_Rows; }
    int GetCols() const { return m_Cols; }
    
    // 填充数组
    void Fill(int value)
    {
        for (int i = 0; i < m_Rows * m_Cols; ++i)
        {
            m_Data[i] = value;
        }
    }
    
    // 打印数组
    void Print() const
    {
        for (int i = 0; i < m_Rows; ++i)
        {
            for (int j = 0; j < m_Cols; ++j)
            {
                std::cout << (*this)(i, j) << " ";
            }
            std::cout << std::endl;
        }
    }
};

int main()
{
    std::cout << "=== 1D Array Simulating 2D (Recommended) ===" << std::endl;
    
    const int rows = 50;
    const int cols = 50;
    
    /* 二维数组转换为一维数组 */
    int* array = new int[rows * cols];
    for (int i = 0; i < rows * cols; i++)
        array[i] = i;

    // 访问第2行第2列的元素(0-based indexing)
    std::cout << "Element at (2,2): " << *((array + cols * 2) + 2) << std::endl;
    
    // 更清晰的访问方式
    auto getElement = [&](int row, int col) -> int& {
        return array[row * cols + col];
    };
    
    std::cout << "Element at (2,2) using lambda: " << getElement(2, 2) << std::endl;
    
    delete[] array;
    
    // 使用封装的Array2D类
    std::cout << "\n=== Using Array2D Class ===" << std::endl;
    Array2D matrix(5, 5);
    
    // 初始化
    for (int i = 0; i < matrix.GetRows(); ++i)
    {
        for (int j = 0; j < matrix.GetCols(); ++j)
        {
            matrix(i, j) = i * matrix.GetCols() + j;
        }
    }
    
    std::cout << "5x5 Matrix:" << std::endl;
    matrix.Print();
    
    return 0;
}

使用std::vector实现多维数组

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#include <iostream>
#include <vector>

template<typename T>
class Vector2D
{
private:
    std::vector<T> m_Data;
    size_t m_Rows, m_Cols;
    
public:
    Vector2D(size_t rows, size_t cols) : m_Rows(rows), m_Cols(cols)
    {
        m_Data.resize(rows * cols);
    }
    
    Vector2D(size_t rows, size_t cols, const T& defaultValue) : m_Rows(rows), m_Cols(cols)
    {
        m_Data.resize(rows * cols, defaultValue);
    }
    
    // 访问元素
    T& operator()(size_t row, size_t col)
    {
        return m_Data[row * m_Cols + col];
    }
    
    const T& operator()(size_t row, size_t col) const
    {
        return m_Data[row * m_Cols + col];
    }
    
    // 安全访问(带边界检查)
    T& At(size_t row, size_t col)
    {
        if (row >= m_Rows || col >= m_Cols)
            throw std::out_of_range("Index out of range");
        return m_Data[row * m_Cols + col];
    }
    
    const T& At(size_t row, size_t col) const
    {
        if (row >= m_Rows || col >= m_Cols)
            throw std::out_of_range("Index out of range");
        return m_Data[row * m_Cols + col];
    }
    
    // 获取维度
    size_t GetRows() const { return m_Rows; }
    size_t GetCols() const { return m_Cols; }
    size_t Size() const { return m_Data.size(); }
    
    // 重置大小
    void Resize(size_t rows, size_t cols)
    {
        m_Rows = rows;
        m_Cols = cols;
        m_Data.resize(rows * cols);
    }
    
    void Resize(size_t rows, size_t cols, const T& defaultValue)
    {
        m_Rows = rows;
        m_Cols = cols;
        m_Data.resize(rows * cols, defaultValue);
    }
    
    // 填充
    void Fill(const T& value)
    {
        std::fill(m_Data.begin(), m_Data.end(), value);
    }
    
    // 获取原始数据
    T* Data() { return m_Data.data(); }
    const T* Data() const { return m_Data.data(); }
    
    // 迭代器支持
    auto begin() { return m_Data.begin(); }
    auto end() { return m_Data.end(); }
    auto begin() const { return m_Data.begin(); }
    auto end() const { return m_Data.end(); }
    
    // 打印(仅适用于可打印类型)
    void Print() const
    {
        for (size_t i = 0; i < m_Rows; ++i)
        {
            for (size_t j = 0; j < m_Cols; ++j)
            {
                std::cout << (*this)(i, j) << " ";
            }
            std::cout << std::endl;
        }
    }
};

// 三维数组模板
template<typename T>
class Vector3D
{
private:
    std::vector<T> m_Data;
    size_t m_Depth, m_Rows, m_Cols;
    
public:
    Vector3D(size_t depth, size_t rows, size_t cols) 
        : m_Depth(depth), m_Rows(rows), m_Cols(cols)
    {
        m_Data.resize(depth * rows * cols);
    }
    
    T& operator()(size_t d, size_t r, size_t c)
    {
        return m_Data[d * m_Rows * m_Cols + r * m_Cols + c];
    }
    
    const T& operator()(size_t d, size_t r, size_t c) const
    {
        return m_Data[d * m_Rows * m_Cols + r * m_Cols + c];
    }
    
    size_t GetDepth() const { return m_Depth; }
    size_t GetRows() const { return m_Rows; }
    size_t GetCols() const { return m_Cols; }
    
    void Print() const
    {
        for (size_t d = 0; d < m_Depth; ++d)
        {
            std::cout << "Layer " << d << ":" << std::endl;
            for (size_t r = 0; r < m_Rows; ++r)
            {
                for (size_t c = 0; c < m_Cols; ++c)
                {
                    std::cout << (*this)(d, r, c) << " ";
                }
                std::cout << std::endl;
            }
            std::cout << std::endl;
        }
    }
};

int main()
{
    std::cout << "=== Vector-based Multidimensional Arrays ===" << std::endl;
    
    // 二维数组
    Vector2D<int> matrix(4, 5, 0);
    
    // 初始化
    for (size_t i = 0; i < matrix.GetRows(); ++i)
    {
        for (size_t j = 0; j < matrix.GetCols(); ++j)
        {
            matrix(i, j) = i * matrix.GetCols() + j;
        }
    }
    
    std::cout << "4x5 Matrix:" << std::endl;
    matrix.Print();
    
    // 三维数组
    std::cout << "\n=== 3D Array ===" << std::endl;
    Vector3D<int> cube(2, 3, 4);
    
    int value = 1;
    for (size_t d = 0; d < cube.GetDepth(); ++d)
    {
        for (size_t r = 0; r < cube.GetRows(); ++r)
        {
            for (size_t c = 0; c < cube.GetCols(); ++c)
            {
                cube(d, r, c) = value++;
            }
        }
    }
    
    cube.Print();
    
    // 使用STL算法
    std::cout << "=== Using STL Algorithms ===" << std::endl;
    Vector2D<double> doubleMatrix(3, 3, 1.0);
    
    // 使用transform填充
    std::transform(doubleMatrix.begin(), doubleMatrix.end(), doubleMatrix.begin(),
                   [](double x) { return x * 2.5; });
    
    std::cout << "Transformed matrix:" << std::endl;
    doubleMatrix.Print();
    
    return 0;
}

性能比较

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <iostream>
#include <vector>
#include <chrono>

void PerformanceComparison()
{
    const int rows = 1000;
    const int cols = 1000;
    const int iterations = 10;
    
    std::cout << "=== Performance Comparison ===" << std::endl;
    std::cout << "Matrix size: " << rows << "x" << cols << std::endl;
    std::cout << "Iterations: " << iterations << std::endl;
    
    // 1. 动态二维数组性能测试
    auto start = std::chrono::high_resolution_clock::now();
    for (int iter = 0; iter < iterations; ++iter)
    {
        int** matrix = new int*[rows];
        for (int i = 0; i < rows; ++i)
        {
            matrix[i] = new int[cols];
        }
        
        // 填充数据
        for (int i = 0; i < rows; ++i)
        {
            for (int j = 0; j < cols; ++j)
            {
                matrix[i][j] = i * cols + j;
            }
        }
        
        // 计算总和(防止编译器优化)
        volatile long long sum = 0;
        for (int i = 0; i < rows; ++i)
        {
            for (int j = 0; j < cols; ++j)
            {
                sum += matrix[i][j];
            }
        }
        
        // 清理
        for (int i = 0; i < rows; ++i)
        {
            delete[] matrix[i];
        }
        delete[] matrix;
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto duration1 = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    // 2. 一维数组模拟二维数组性能测试
    start = std::chrono::high_resolution_clock::now();
    for (int iter = 0; iter < iterations; ++iter)
    {
        int* array = new int[rows * cols];
        
        // 填充数据
        for (int i = 0; i < rows * cols; ++i)
        {
            array[i] = i;
        }
        
        // 计算总和
        volatile long long sum = 0;
        for (int i = 0; i < rows; ++i)
        {
            for (int j = 0; j < cols; ++j)
            {
                sum += array[i * cols + j];
            }
        }
        
        delete[] array;
    }
    end = std::chrono::high_resolution_clock::now();
    auto duration2 = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    // 3. std::vector性能测试
    start = std::chrono::high_resolution_clock::now();
    for (int iter = 0; iter < iterations; ++iter)
    {
        std::vector<int> vec(rows * cols);
        
        // 填充数据
        for (int i = 0; i < rows * cols; ++i)
        {
            vec[i] = i;
        }
        
        // 计算总和
        volatile long long sum = 0;
        for (int i = 0; i < rows; ++i)
        {
            for (int j = 0; j < cols; ++j)
            {
                sum += vec[i * cols + j];
            }
        }
    }
    end = std::chrono::high_resolution_clock::now();
    auto duration3 = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    std::cout << "\nResults:" << std::endl;
    std::cout << "Dynamic 2D array: " << duration1.count() << " ms" << std::endl;
    std::cout << "1D array (simulating 2D): " << duration2.count() << " ms" << std::endl;
    std::cout << "std::vector: " << duration3.count() << " ms" << std::endl;
    
    std::cout << "\nSpeedup vs Dynamic 2D:" << std::endl;
    std::cout << "1D array: " << (double)duration1.count() / duration2.count() << "x" << std::endl;
    std::cout << "std::vector: " << (double)duration1.count() / duration3.count() << "x" << std::endl;
}

int main()
{
    PerformanceComparison();
    return 0;
}

实际应用:图像处理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>

class Image
{
private:
    Vector2D<unsigned char> m_Data;
    size_t m_Width, m_Height;
    
public:
    Image(size_t width, size_t height) : m_Width(width), m_Height(height), m_Data(height, width, 0) {}
    
    unsigned char& Pixel(size_t x, size_t y) { return m_Data(y, x); }
    const unsigned char& Pixel(size_t x, size_t y) const { return m_Data(y, x); }
    
    size_t GetWidth() const { return m_Width; }
    size_t GetHeight() const { return m_Height; }
    
    // 应用简单的模糊滤镜
    void ApplyBlur()
    {
        Vector2D<unsigned char> temp(m_Height, m_Width);
        
        for (size_t y = 1; y < m_Height - 1; ++y)
        {
            for (size_t x = 1; x < m_Width - 1; ++x)
            {
                int sum = 0;
                for (int dy = -1; dy <= 1; ++dy)
                {
                    for (int dx = -1; dx <= 1; ++dx)
                    {
                        sum += Pixel(x + dx, y + dy);
                    }
                }
                temp(y, x) = sum / 9;
            }
        }
        
        m_Data = std::move(temp);
    }
    
    // 生成随机噪声
    void GenerateNoise()
    {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> dis(0, 255);
        
        for (size_t y = 0; y < m_Height; ++y)
        {
            for (size_t x = 0; x < m_Width; ++x)
            {
                Pixel(x, y) = dis(gen);
            }
        }
    }
    
    // 简单的ASCII艺术显示
    void PrintASCII() const
    {
        const char* chars = " .:-=+*#%@";
        const int numChars = 10;
        
        for (size_t y = 0; y < m_Height; y += 2)  // 每两行取一行
        {
            for (size_t x = 0; x < m_Width; x += 2)  // 每两列取一列
            {
                int intensity = Pixel(x, y);
                int charIndex = (intensity * numChars) / 256;
                if (charIndex >= numChars) charIndex = numChars - 1;
                std::cout << chars[charIndex];
            }
            std::cout << std::endl;
        }
    }
};

int main()
{
    std::cout << "=== Image Processing Example ===" << std::endl;
    
    Image img(40, 20);
    img.GenerateNoise();
    
    std::cout << "Original noisy image:" << std::endl;
    img.PrintASCII();
    
    img.ApplyBlur();
    
    std::cout << "\nAfter blur filter:" << std::endl;
    img.PrintASCII();
    
    return 0;
}

总结

  1. 多维数组实现方式
    • 静态数组:编译时确定大小
    • 动态指针数组:运行时分配,但内存不连续
    • 一维数组模拟:推荐方法,内存连续,性能更好
  2. 推荐方法:将多维数组转换为一维数组,因为在动态内存分配时更加高效,而且也更简单
  3. 访问公式:对于二维数组,array[row * cols + col]
  4. 性能优势
    • 内存连续分配
    • 更好的缓存局部性
    • 更简单的内存管理
  5. 现代C++方法:使用std::vector和模板类封装,提供类型安全和异常安全
  6. 实际应用:图像处理、矩阵运算、游戏开发等领域广泛使用
updatedupdated2025-09-202025-09-20