简体   繁体   中英

Initializing multidimensional array C++

In C++, when I want to initialize an array of some length (of integers for instance) I can just write

int* tab;
tab = new int[size];

where size is given somewhere else. But how do I do that in the same manner, when it comes to a multidimensional array? I can't just add another dimension(s) in the second line, because compiler doesn't like that...

It's a simple question I guess. I need that, as I'm writing an assignment in object-oriented programming and 2D array is a private part of a class, which needs to be... constructed in the constructor (with 2 dimensions as parameters).

Using std::vector is the safe way:

std::vector<std::vector<int>> mat(size1, std::vector<int>(size2));

if really you want to use new yourself:

int** mat = new int*[size1];
for (std::size_t i = 0; i != size1; ++i) {
    mat[i] = new int[size2];
}

And don't forget to clean resources:

for (std::size_t i = 0; i != size1; ++i) {
    delete [] mat[i];
}
delete[] mat;

If you can afford std::vector instead of arrays you can use as syntax:

std::vector< std::vector<int> > matrix(rows, std::vector<int>(columns));

for (int i=0; i<rows; i++) {
    for (int j=0; j<columns; j++) {
        matrix[i][j] = i+j;
    }
}

If you get height/width parameters before the initialization of the array you can try:

int height = 10;
int width = 10;

//...

int tab[heigth][width];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM