Gal Aharon
Gal Aharon

Reputation: 61

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

Upvotes: 0

Views: 2425

Answers (3)

Lordbug
Lordbug

Reputation: 119

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

Upvotes: 1

TooBoredToWriteAName
TooBoredToWriteAName

Reputation: 23

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;

Upvotes: 1

Ihor Dobrovolskyi
Ihor Dobrovolskyi

Reputation: 1241

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

Upvotes: 0

Related Questions