STL vector

#include <vector>
using namespace std;

int main() {
    // construct array2D[HEIGHT][WIDTH]
    vector<vector<double> > array2D;

    array2D.resize(HEIGHT);
    for (int i = 0; i < HEIGHT; ++i)
        array2D[i].resize(WIDTH);


    // construct array3D[HEIGHT][WIDTH][DEPTH]
    vector<vector<vector<double> > > array3D;

    array3D.resize(HEIGHT);
    for (int i = 0; i < HEIGHT; ++i) {
        array3D[i].resize(WIDTH);
        for (int j = 0; j < WIDTH; ++j)
            array3D[i][j].resize(DEPTH);
        }

    return 0;
}

这种方法的好处是不用自己手动释放内存,而且数组大小可以动态变化(不过通常我们使用多维数组时不会变化它的大小)。
缺点是比较丑陋,一串vector会很长,尤其是> >不能连在一起否则编译器会认为是移位或者流提取运算符,尽管在c++11中可以连在一起写了。

指针

int main() {
    // construct p2DArray[HEIGHT][WIDTH]
    double **p2DArray;

    p2DArray = new double*[HEIGHT];
    for (int i = 0; i < HEIGHT; ++i)
        p2DArray[i] = new double[WIDTH];

    for (int i = 0; i < HEIGHT; ++i)
        delete [] p2DArray[i];
    delete [] p2DArray;


    // construct p3DArray[HEIGHT][WIDTH][DEPTH]
    int ***p3DArray;

    p3DArray = new int**[HEIGHT];
    for (int i = 0; i < HEIGHT; i++) {
        p3DArray[i] = new int*[WIDTH];
        for (int j = 0; j < WIDTH;j++) {
            p3DArray[i][j] = new int[DEPTH];
        }
    }

    for (int i = 0; i < HEIGHT; ++i) {
        for (int j = 0; j < WIDTH; ++j) {
            delete [] p3DArray[i][j];
        }
        delete [] p3DArray[i];
    }
    delete [] p3DArray;
}

这样的数组简洁明了,但要自己手动释放内存, 顺序还不能错,比较容易出问题。

参考

http://www.cplusplus.com/forum/articles/7459/

载入中...