Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a multidimentional array without the size

I want to declare an array of arrays or multidimensional array without knowing the size.

I want to do something similar to what I did in this cases with simple arrays:

int *array;
cin >> size;
array = new int[size];

Maybe I can loop to initialize a pointer of pointers like this:

int **array;
cin >> rows >> col;
array = new *int[rows]
for (int i = 0; i < rows; ++i)
    array[i] = new int[col];

But I would prefer to not do this if a better solution exists.

like image 890
blackløtus Avatar asked Oct 10 '12 23:10

blackløtus


2 Answers

Why not use std::vector?

std::vector<std::vector<int> > array;

If you don't want to use an array of pointers, you could use one large array that you allocate dynamically after you get the size and access it as an array of rows.

int rows = 10;
int columns = 20;

int* array = new int[rows * columns];

for (int count = 0; count < rows; count++)
{
   int* row = &array[count * columns];

   for (int inner_count = 0; inner_count < columns; inner_count++)
   {
      int* element = &row[inner_count];

      //do something
   }
}

delete [] array;
like image 151
Geoff Montee Avatar answered Nov 12 '22 19:11

Geoff Montee


You're pretty much going to have to go with the loop version. You can make one slight improvement, which is to allocate one big block and then build your own int* index into it:

int **array;
int *storage;
cin >> rows >> col;
array = new *int[rows];
storage = new int[rows*col];
for (int i = 0; i < rows; ++i)
    array[i] = storage + col * i;

This has the nice property that you can still use array[i][j] syntax for accessing the array.

like image 29
sblom Avatar answered Nov 12 '22 19:11

sblom