在C++

问题描述:

在java中多维数组,对象的多维数组diclared这样的(A为对象的类型):在C++

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++?

+0

您可以使用'的std ::向量>'做在C++相同。 –

+0

可能的重复[如何在C++中使用数组?](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c) –

+0

它不一样....我需要使**对象**数组而不是**变量**数组(例如浮点数或整数) –

可以很容易地使用这样的代码:

A array[5][5]; 

它将创建2D阵列,它将初始化每个单元与一个目的。这一段代码等于在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; 
} 
+0

它与我在java中编写的代码相同....无论如何,当我编译此代码时,出现错误: –

+0

它在另一个文件中。我将它导入到主文件的开头。 –

+0

数组创建正确,问题出在您的代码上。请发布您的代码,或者针对您现在遇到的问题创建另一个问题。 –

一个多维数组另一个想法是,如果你使用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 }}; 

,你只需按行声明值,每行都是一组大括号,然后用最后一组括号括起整个表格。

如果你是在爱与循环你仍然可以使用它们:

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