I have a Matrix class and I want to pass an array to the constructor in order to set the values of the matrix dynamically. I found that if I allocate an array like this:
double **array;
array = new double*[3];
array[0] = new double[2];
array[1] = new double[2];
array[2] = new double[2];
array[0][0] = 1;
array[0][1] = 1;
array[1][0] = 1;
array[1][1] = 1;
array[2][0] = 1;
array[2][1] = 1;
I can get the number of rows and cols using a method like this:
int getNRows(double **data){
int size = 0;
while(*(data+size)){size++;}
return size;
}
int getNCols(double **data){
int size = 0;
while(**(data+size)){size++;}
return size;
}
Is this ok or should I stick to the vector declaration?
Your assumption is totally wrong; you cannot obtain the size in any way close to what you propose. That’s utterly undefined and dangerous behaviour.
Here’s a pseudo-rule (i.e. it’s not true, but unless you understand why it’s not true, it applies to you):
Don’t use pointers. Don’t use
newanddelete. (And don’t sayusing namespace std;.)The one and only way in which you should be doing this is with C++ containers.
A vector of vectors would be the first shot, though a flat vector accessed in strides may be better, and Boost.multi_array may even be the best:
std::vector< std::vector<double> > v (3, std::vector<double>(2));std::array<std::array<double, 2>, 3>std::vector<double> v(6);, and usev[i + 2 *j]etc.Boost.MultiArray