I am trying to create a simple matrix class. When an object of class matrix is created it should be able to create any nxn size matrix. The problem I am finding is that there doesn't seem to be a simple way to make a class with a dynamic 2D array. Most of the examples I find online are extremely complicated. Any advice on I might solve this? Any links that might help or code snippets to aide would be greatly appreciated.

#include<iostream>
using namespace std;

class Matrix
{
public:
	Matrix();
	Matrix(int r, int c);
private:

	int rowNumber;  	//number of row in the matrix
	int colNumber;	//number of columns in the matrix
};
Matrix::Matrix()
{
	rowNumber=0;  	
	colNumber=0;
}
Matrix::Matrix(int r, int c)
{
	rowNumber=r;  	
	colNumber=c;

}
int main()
{
	return 0;
}

You should use 2D vectors.

I don't know if you know them, but they are nearly the same as arrays, just if you want to add a cell, you have to use vectorname.push_back(X).

By 2D vectors I think he means

std::vector<std::vector<double> >

.

Also, is this for an assignment? If not, you should definitely stick with a matrix class that is already made - vnl_matrix from the VXL package or something like that. It will save you lots of headaches.

Dave

Programming can be fun; so if you want to do it by yourself, you could use structure arrays and replace each row of your matrix by an instance of a structure. An advantage: the rows can have different lengths. The comments and additions to your program shown below are for a public matrix, so that I didn't use the private variables rowNumber and colNumber.

#include<iostream>
using namespace std;

const int maxrownbr = 100;		//maximum row number of matrices used in your program

class Matrix
{
public:
	Matrix();
	Matrix(int r, int c);
	struct row					//defines a structure array: a structure instance for 
	{							//each matrix row
		double *matelt;
	};

private:

	int rowNumber;  	//number of row in the matrix
	int colNumber;	//number of columns in the matrix
};
Matrix::Matrix()
{
	rowNumber=0;  	
	colNumber=0;
}
Matrix::Matrix(int r, int c)
{
	struct row rowinst[maxrownbr];					//defining enough structure instances
	for( int irow=0; irow<r; irow++ )				//to allocate one for each row
		rowinst[irow].matelt = new double[c];		//each row is a one-dimensional array:  
													//memory allocation

	for( int i=0; i<r; i++ )						//filling the matrix for testing
	{
		for( int j=0; j<c; j++ )
		{
			rowinst[i].matelt[j] = c*i + j;
			cout << rowinst[i].matelt[j] << "  ";
		}
		cout << endl;
	}

	rowNumber=r;  	
	colNumber=c;

}
int main()
{
	int r=2;
	int c=3;
	Matrix::Matrix(r,c);
	return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.