简体   繁体   English

初始化多维数组C ++

[英]Initializing multidimensional array C++

In C++, when I want to initialize an array of some length (of integers for instance) I can just write 在C ++中,当我想初始化一些长度(例如整数)的数组时,我可以写

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). 我需要这样,因为我在面向对象编程中编写了一个赋值,而2D数组是一个类的私有部分,它需要在构造函数中构造(以2维作为参数)。

Using std::vector is the safe way: 使用std::vector是安全的方法:

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

if really you want to use new yourself: 如果真的想要自己使用new

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< 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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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