简体   繁体   中英

multidimensional array in c++

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

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;

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

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

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