Declare a dynamic matrix

I would write this down as an application for future using.

We know matrix (array 2D) is cornerstone in computation. The issue is if we declare array in C++, it requires fixed dimensions in compilation (it means we can provide dimensions of matrices when programs are running). To avoid this inconvenience, there are two 2 ways in C++ (in my limit knowledge):

  1. Using pointers
  2. Using vector of STL

USING POINTERS:

If the matrices are 1D, the declaration is:

#include<iostream>
using namespace std;
int main(){
	double *matrix;
	int dimension;
	cin>>dimension;
	matrix=new double[dimension];
}

For 2D matrices, the declaration is:

#include<iostream>
using namespace std;
int main(){
	double **matrix;
	int rowN,colN;
	cin>>rowN;
	cin>>colN;
	matrix=new double*[rowN];
	for(int ii=0;ii<rowN;++ii){
		matrix[ii]=new double[colN];
		for(int jj=0;jj<colN;++jj){cin>>matrix[ii][jj];}
	}
}

USING VECTORS;

1D matrices:

#include<iostream>
#include<vector>
using namespace std;
int main(){
	vector<double> matrix;
	int dimension;
	cin>>dimension;
	matrix.resize(dimension);
}

2D matrices:

#include<iostream>
#include<vector>
using namespace std;
int main(){
	vector<vector<double> > matrix;
	int rowN,colN;
	cin>>rowN;
	cin>>colN;
	matrix.resize(rowN);
	for(int ii=0;ii<rowN;++ii){
	    matrix[ii].resize(colN);
	}
}

That’s all I know. Hope I can get some more methods in this aspect.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s