multidimensional array in c++

一笑奈何 提交于 2020-02-07 08:21:33

问题


In java, multidimensional arrays of objects diclared like this (A is type of object):

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();
    }
}

how can I do the same in C++?


回答1:


Another idea for a multi dimensional array is if you use 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);
   }
}

The good thing about a vector is that there is no limit to the amount of items;




回答2:


Unless I have misunderstood your question in some way, to declare a two-dimensional array in C++ you could use this:

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

If you think of a two-dimensional array as a virtual table, you just declare the values by row, each row is a set of curly brackets, then surround the whole table with a final set of brackets.

If you are in love with for loops you can still use them:

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



回答3:


You can easily use the code like this:

A array[5][5];

It will create the 2D array and it will initialize each cell with A object. This piece of code equals to the code in Java like this:

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();
    }
}

Full code which works properly:

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


来源:https://stackoverflow.com/questions/41312092/multidimensional-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!