An array of array of int type

Started by
5 comments, last by Alundra 6 years, 11 months ago

I want to create an array of array of int type arrays. Can anyone help me?

Advertisement

it's not clear to me so 3 options :

Array of array of int


​std::vector< std::vector< int > >

Array of array of int*


std:vector< std::vector< int* > >

Array of array of array of int


std::vector< std::vector< std::vector< int > > >

If the size is fixed you can simply do :


int* array[10][10]

or


int array[10][10][10]

This looks right although I don't know what std means. Option 1 looks perfect.

std is the namespace used for the standard library of c++.
Maybe are you doing :


using namespace std;

If the answer is yes, then I hardly recommend to not do.

std is the namespace used for the standard library of c++.
Maybe are you doing :


using namespace std;
If the answer is yes, then I hardly recommend to not do.


This topic is tagged "Java", so I don't know why we are talking about C++ idioms.

In Java, you can create jagged arrays either as array objects or as containers of containers. You still need to create each instance:


int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[10];
jaggedArray[2] = new int[17];

You can also do this with a collection, ArrayList is the preferred type.


ArrayList< ArrayList<int> > collectionOfCollections = new ArrayList< ArrayList<int> >();
collectionOfCollections.add( new ArrayList<int>() );
collectionOfCollections.add( new ArrayList<int>() );

If you don't need a jagged array, it is usually better to have a flat array and access a position within it. That prevents the cost of multiple indirections needed for looking up within the first array, then looking up within the second array; instead you can easily compute the index and use a single indirection to find it.


int[] myArray = new int[Width * Height];
...
index = y*Width + x;  // Row major, walking the array goes through each x, then advances one y and through each x again
OR
index = x*Height + y; // Column major, walking the array goes through each y, then advances one x and through each Y again

You will want to replace those with named constants rather than numbers, and probably put the object creation inside loops rather than calling them individually, but that should be enough to get started.

This topic is tagged "Java", so I don't know why we are talking about C++ idioms.

Good point, I simply clicked on the home page and answered.

This topic is closed to new replies.

Advertisement