I am trying to write a class in c++ which will contain a 2D array member variable. The point of the class is to represent a simulated physical model using this array, and I intended to write the various actions I want to perform on the array as member functions.
My problem is trying to initialise the array in the class without hard coding it- ideally, I would like to write the overall program so that the dimension of the array can be inputted by the user at the run time, and this can then be used in the overload constructor for the class. i.e. something like this:
class Lattice{
public:
//Overload constructor
Lattice(int);
private:
//variables:
int DimensionSize;
int lattice[DimensionSize][DimensionSize];
}
Lattice::Lattice(int N){
DimensionSize = N;
lattice = new int[DimensionSize][DimensionSize];
}
I can see that the code above clearly won't work, as the variable "DimensionSize" is unspecified at runtime, which means the amount of memory required for the 2d array "lattice" is unknown.
I've been looking around on this forum for an answer for this but there doesn't seem to be anything directly helpful for my issue, and any other questions that have been asked seem quite old. If anyone could point me towards a solution, or let me know if what I want is even possible it would be greatly appreciated- I wonder if using a vector instead of an array may be a solution?
Update:
I was able to produce the behaviour that I wanted by using a template class:
template <int N>
class Lattice
{
public:
//Constructor
Lattice();
~ some other functions ~
private:
float lattice[N][N];
};
template <int N>
Lattice<N>::Lattice() {
double rando;
// Initialise the array to a random state.
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++){
rando = (double)rand() / ((double)RAND_MAX + 1);
if( rando <= 0.5 ){
lattice[i][j] = -1.0;
}
else if( rando >= 0.5 ){
lattice[i][j] = 1.0;
}
}
}
}
I can see using vectors instead of arrays is possible, so my question now is there any major downsides to using a template as above? I can see that the class declaration and definition now have to be contained in the same header file, as outlined in this thread Why can templates only be implemented in the header file? but are there any other problems that may arise apart from this inconvenience?