Pregunta

In a class, i want to create an array (predefined because it's in a header class) without specifying any bounds until the class has an object created with it's type. For example:

class RandomClass{
public:
    int myarray[][];//Remember this is a 2D array, 1D arrays can be defined like this.
}

(This class is incomplete, i know, just pretend its not) Obviously this doesn't work because "i'm not allowed to create an array without defining its bounds"

So my question is, how can i do this? Or maybe, how do i create an array inside the constructor of the class that will be accessed publicly to the class's members.

For a little bit of information on why i want to do this; I am trying to create a class that handles maps for a 2D game, when the class is created it will be given the size of the map through it's constructor's parameters, then the array will be created so that it doesn't need to be any bigger than the size of the map itself. I know i could possibly use vectors, however I have difficulty making them 2 Dimensional. (If you answer my question, please answer the main question first, don't just tell me how to use a vector in this situation - However it would be helpful too)

I will post the error, although there isn't much of a reason to.

error: declaration of 'myarray' as multidimensional array must have bounds for all dimensions except the first

¿Fue útil?

Solución

The answer to the first question is

int** myarray;

then in your constructor

RandomClass(int rows, int cols)
{
    myarray = new int*[rows];
    for (int i = 0; i < rows; ++i)
        myarray[i] = new int[cols];
}

The answer to the second question is

vector< vector<int> > myvector;

A 2D vector is simply a vector of vectors, then in your constructor

RandomClass(int rows, int cols) : myvector(rows, vector<int>(cols))
{
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top