Variable-length 2-D arrays of doubles?
Is there a way to have variable-length 2-D arrays of doubles in MS C++? These are arrays whose dimensions are not known at compile time.
I want to have the compiler do the calculation of the position in the array; I do not want to write code to do this. In other words, I want the syntax to be A
[j]. I am not interested in the "solution"
double *p; p[j*n+i];
Maybe using array of arrays could be the answer?
double ** array = new double*[arrayLength1];
then for every element of array create the double array for example:
array[0] = new double[arrayLength2];
The other alternative and the one which I prefer myself is to use STL like this:
vector< vector<double> > my2dArray;
In both cases second dimension of the array has to be set for every "row" but if you want a "jagged" array then it is a plus.
You can use dynamic memory allocation as said in the previous reply by PaulDotNetPlease see a re-useable code by Dr.GUI in MSDN on Implementing 2 Dimensional array.
See the original article here
#include <vector>
using namespace std;
template <class T>
class C2DVector
{
public:
C2DVector():m_dimRow(0), m_dimCol(0){;}
C2DVector(int nRow, int nCol) {
m_dimRow = nRow;
m_dimCol = nCol;
for (int i=0; i < nRow; i++){
vector<T> x(nCol);
int y = x.size();
m_2DVector.push_back(x);
}
}
void SetAt(int nRow, int nCol, const T& value) throw(std::out_of_range) {
if(nRow >= m_dimRow || nCol >= m_dimCol)
throw out_of_range("Array out of bound");
else
m_2DVector[nRow][nCol] = value;
}
T GetAt(int nRow, int nCol) {
if(nRow >= m_dimRow || nCol >= m_dimCol)
throw out_of_range("Array out of bound");
else
return m_2DVector[nRow][nCol];
}
void GrowRow(int newSize) {
if (newSize <= m_dimRow)
return;
m_dimRow = newSize;
for(int i = 0 ; i < newSize - m_dimCol; i++) {
vector<int> x(m_dimRow);
m_2DVector.push_back(x);
}
}
void GrowCol(int newSize) {
if(newSize <= m_dimCol)
return;
m_dimCol = newSize;
for (int i=0; i <m_dimRow; i++)
m_2DVector
.resize(newSize);
}
vector<T>& operator[](int x) {
return m_2DVector[x];
}
private:
vector< vector <T> > m_2DVector;
unsigned int m_dimRow;
unsigned int m_dimCol;
};