How can I get the number of rows and columns of a 2-D dynamic array in c++ -
i trying make functions(adding, subtracting, product, etc) taking arguments dynamic 2-d arrays.
for example, given 2 2-d double arrays each 1 having 2 rows , 2 columns:
double** m1; m1 = new double *[2]; (int = 0; < 2; ++i) { m1[i] = new double[2]; } double k1 = 1.0; (int = 0; < 2; ++i) { (int j = 0; j < 2; ++j) { m1[i][j] = k1; k1 += 2.0; } } double** m2; m2 = new double *[2]; (int = 0; < 2; ++i) { m2[i] = new double [2]; } double k2 = 2.0; (int = 0; < 2; ++i) { (int j = 0; j < 2; ++j) { m2[i][j] = k2; k2 += 2.0; } }
and made adding function them. first checks whether 2 arrays have same numbers of rows , columns. arrays totally dynamic(both numbers of rows , columns) , declared pointers pointers, can't numbers of rows , columns.
for example, value of
sizeof(m1[0])
is 4, is, bite size of double pointer (probably) but, value of
sizeof(m1[0][0])
is 8 right size of double type.
i want adequate version of former.
double** add_m(double **m1_, double** m2_) { //here first part needs numbers of arguments' rows , columns. if ((sizeof(*m1_) != sizeof(*m2_)) || (sizeof(**m1_) != sizeof(**m2_))) { cout << "the sizes of matrices don't match each other"; return 0; } else { //here second part needs numbers of arguments' rows , columns. int num_rows = sizeof(m1_[0])/sizeof(m1[0][0]);//?? int num_cols = sizeof(m1_[0][0])/sizeof(m1_[0][0]);//?? double** res; res = new double*[num_rows]; (int = 0; < num_rows; ++i) { res[i] = new double[num_cols]; } (int = 0; < num_rows; ++i) { (int j = 0; j < num_cols; ++j) { res[i][j] = m1_[i][j] + m2_[i][j]; } } return res; } }
edit: of answers using existing tools vector, matrix. curiosity, no way of doing it? way making vector-like class or matrix-like class scratch?
it seems want handle matrices.
unfortunatelly, dynamic memory allocation doesn't store size of allocated memory.
these alternatives:
store matrix dimensions yourself
then need pass matrix dimensions parameter functions. example, this:
double** add_m(double **m1_, double** m2_, unsigned width, unsigned height)
use std::array or std::vector
these classes store number of elements.
#include <array> #include <vector> using namespace std; // ... array<array<double, 3>, 3> m1 = {{ {1, 0, 0}, {0, 1, 0}, {0, 0, 1} }}; unsigned height = m1.size(); unsigned width = m1[0].size(); vector<vector<double> > m2 = {{ {0, 1, 0}, {1, 0, 0}, {0, 0, 1} }}; height = m2.size(); width = m2[0].size();
make own matrix class
that keeps track of number of elements , encapsulates operations can done them.
use external library defines "matrix" class
if make quick google search find tone (keywords: linear algebra library).
these tested , liked:
- eigen (any dimension, supports sparse matrices)
- glm (up 4x4 matrices, uses simd faster computations)
Comments
Post a Comment