multidimensional dynamic matrix how can i create one?
I am working in C++ on Ubuntu. I would like to know how to开发者_运维问答 create a matrix with dynamic length?
I did this: int matrix[12][]
but it's not working. The dimension for the columns will increase step by step in my code. Can someone show me the correct code in an example?
int ** matrix;
matrix = new int* [rowcount];
for (int i = 0; i<rowcount; ++i)
{
matrix[i] = new int[colcount]
}
To clean this up:
for(int i = 0; i < rowcount; ++i)
delete [] matrix[i];
delete [] matrix;
Of course, when you use vectors, memory management is done automatically;
vector<vector<int> > matrix(rowcount, vector<int>(colcount));
You might want to have a look at the boost ublas
library. Its a numerical library - so has the operations you expect, such as matrix multiplication - but is c++-std like in the sense that it accepts arbitrary types via templates (like the std::vector<Type>
).
You can find the documentation here, with the matrix type here
Pros:
- Its does your memory management for you,
- Its efficient
- It already has a host of algorithms for you to use (which you would have to re-write if you did a
vector<vector<type> >
matrix)
Cons:
- Adding rows and columns dynamically is not possible - you have to copy the entire matrix into a new, larger matrix.
I may use vector
.
typedef std::vector< std::vector<int> > Matrix;
Matrix matrix;
matrix.resize(12); // 12 rows.
// Add one more coulmn
for ( Matrix::iterator iter = matrix.begin(); iter != matrix.end(); ++iter )
(*iter).push_back(new_column_value);
If the number of columns changes in the course of your program, but the number of rows does not (this is how I read your question), then you should represent your matrix as column-major. This means, the first index should represent columns, and the second index should represent rows. Then, represent your matrix as std::vector< std::vector<int> >
. Now, if you want to add a column, you just add another vector. If you stored the matrix row-major, you would have to resize all the inner vectors to add an additional column.
If you want to use the indeces row-major anyway (because that is the convention), you can wrap the matrix in a class to switch the indices.
You can to use Vectors for this purpose.
the simpliest way to create matrix which dynamically change its size would be something derived from vector<vector<int> >
you should add some functions about resizing, because if you add new row to you matrix vector won't add columns automatically, and it will be what you need.
class myMatrix:public vector<vector<int> >
{
...
bool resize(int x, int y)
{
resize(x);
for(vector<vector<int> >::iterator iter = begin(); iter !=end(); ++iter)
(*iter).resize(y);
}
}
精彩评论