Sunday, July 12, 2009

Creating a variable array in c++?

The problem I have is that I want to create a 2D array that has a variable size. I see that I can not do the following:





int m, n;


double testarray[m][n];





as c++ will not let me declare variables for the size. How would I get around this? Perhaps you could write a little code for me to illistrate this?





Thank you,





Brian

Creating a variable array in c++?
There is several otion easiest one is using double pointer though many people are not comfortable with pointer.


Using double pointer,


double ** testarray;


testarray= new double* [m];


for(i=0;i%26lt;m;i++)


testarray[i]= new double [n];





now you can use this test array as before.
Reply:The Boost project (http://www.boost.org/) provides free peer-reviewed portable C++ source libraries. Many of these are candidates for inclusion in a future revision of the C++ language standard. In fact, the Boost project was started by members of the C++ standards committee's library subcommittee, to develop libraries that everyone agreed were needed in C++ but weren't ready at the time the C++ standard was released.





Boost libraries are reviewed, thoroughly tested, and documented. They are in wide use and are portable to nearly all platforms that run C++.





One of the Boost libraries is the Multidimensional Array Library


(Boost.MultiArray). From the docs:





"The Boost Multidimensional Array Library provides a class template for multidimensional arrays, as well as semantically equivalent adaptors for arrays of contiguous data. ... Boost MultiArray is a more efficient and convenient way to express N-dimensional arrays than existing alternatives (especially the std::vector%26lt;std::vector%26lt;...%26gt;%26gt; formulation of N-dimensional arrays). The arrays provided by the library may be accessed using the familiar syntax of native C++ arrays. Additional features, such as resizing, reshaping, and creating views are available..."
Reply:You're only permitted to use variable value for the left-most array dimension ... this is because indexes into the array for the other dimensions need to be constant to calculate where in the array to begin the offset.





But you can simply allocate space for a one-dimensional array of the size necessary for the two-dimensional array (i.e. double testarray[m * n]) and then access elements as :





testarray[(X * n) + Y)] ... where X and Y are the row/column or column/row of the element you are seeking.





This can be expanded to work for any number of dimensions.


No comments:

Post a Comment