繁体   English   中英

C ++中的多维数组

[英]multidimensional array in c++

在Java中,这样声明的对象的多维数组(A是对象的类型):

A[][] array = new A[5][5];

for(int i = 0;i<5;i++){
    for(int j = 0;j<5;j++){
        array[i][j] = new A();
    }
}

我如何在C ++中做同样的事情?

多维数组的另一个想法是,如果您使用std :: vector

#include <vector>

class A{
//Set properties here
};

int main(){

   //Init vector
   std::vector<std::vector<A>> array;

   std::vector<A> tempVec;

   for(int i = 0;i<5;i++){

       for(int j = 0;j<5;j++){
           A aValue;

           //Set properties for object A here

           tempVec.push_back(aValue);
       }
       array.push_back(tempVec);
   }
}

向量的好处是对项目数量没有限制。

除非我以某种方式误解了您的问题,否则可以在C ++中声明一个二维数组,您可以使用以下代码:

A variable; // Declares a variable of A type, named variable
A array[5][5] = {{ variable, variable, variable, variable, variable },
                        { variable, variable, variable, variable, variable },
                        { variable, variable, variable, variable, variable },
                        { variable, variable, variable, variable, variable },
                        { variable, variable, variable, variable, variable }};

如果将二维数组视为虚拟表,则只需按行声明值,每行是一组花括号,然后用最后一组括号包围整个表。

如果您喜欢for循环,则仍然可以使用它们:

A variable;
A array[5][5];
for (int row = 0; row < 5; row++){
    for (int col = 0; col < 5; col++){
        array[row][col] = variable;
    }
}

您可以轻松地使用如下代码:

A array[5][5];

它将创建2D数组,并使用A对象初始化每个单元格。 这段代码等于Java中的代码,如下所示:

A[][] array = new A[5][5];

for(int i = 0;i<5;i++){
    for(int j = 0;j<5;j++){
        array[i][j] = new A();
    }
}

完整的代码可以正常工作:

class A{};
int main() {
    A array[5][5];
    return 0;
}

暂无
暂无

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

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