To create a two-D array of doubles using C++ STL templates:
I used vector of doubles as follows:
vector< vector <double> > arrayname;
I got this tip from yolinux. As can be seen, it is a vector of vectors. C++ STL templates come with a cost of cumbersome access to elements. Please bear in mind that random access is not easy with this.
If you want to do some matrix manipulation, I would suggest you declare a two-dimensional array using pointer to a array of pointers as follows (here, val is the arrayname):
double **val;
val = (double**) malloc(sizeof(double*) * listsize);
val[0] = (double*)malloc(sizeof(double)* listsize * numcols);
for (i = 1; i < listsize; i++)
val[i] = val[i-1]+numcols;
Basically, we dump all elements to the location pointed by first pointer in the array of pointers and make our life easier for ease of access to array elements by setting the other pointer locations in relation to the first one. When you don't do this, you will have to map two-d index values onto one-d. Don't forget to free the pointers after done with using them (in order):
free(val[0]);
free(val);
Thanks to Numerical Recipes in C, I learnt the correct way of declaring and allocating two-dimensional arrays in C/C++.
I used vector of doubles as follows:
vector< vector <double> > arrayname;
I got this tip from yolinux. As can be seen, it is a vector of vectors. C++ STL templates come with a cost of cumbersome access to elements. Please bear in mind that random access is not easy with this.
If you want to do some matrix manipulation, I would suggest you declare a two-dimensional array using pointer to a array of pointers as follows (here, val is the arrayname):
double **val;
val = (double**) malloc(sizeof(double*) * listsize);
val[0] = (double*)malloc(sizeof(double)* listsize * numcols);
for (i = 1; i < listsize; i++)
val[i] = val[i-1]+numcols;
Basically, we dump all elements to the location pointed by first pointer in the array of pointers and make our life easier for ease of access to array elements by setting the other pointer locations in relation to the first one. When you don't do this, you will have to map two-d index values onto one-d. Don't forget to free the pointers after done with using them (in order):
free(val[0]);
free(val);
Thanks to Numerical Recipes in C, I learnt the correct way of declaring and allocating two-dimensional arrays in C/C++.
No comments:
Post a Comment