C++ 2D growing array like MATLAB
I have read some posts about dynamic growing arrays in C, but I can't see how to create a 2D growing array (like in MATLAB).
I have a function to construct an array for some image processing, but I don't know what will be 开发者_开发问答the size of this array (cols and rows). How can I create this?
I read something about malloc and realloc. These functions are portable or useful for this problem.
EDIT: SOLVED, using the Armadillo library, a C++ linear algebra library.
Simplest is with pointers
int nrows = 10;
int ncols = 5;
double* matrix = new double[mrows*ncols];
And then you can access it as if it's a 2D array like.
So if you want matrix[row][col]
, you'd do
int offset = row*ncols+col;
double value = matrix[offset];
Also, if you want the comfort of Matlab like matrixes in C++, look into Armadillo
If you're doing image processing, you might want to use the matrix and array types from opencv.
By growing an array like Matlab, I'm assuming you mean doing things like:
mat = [mat; col]
You can resize a matrix in C++, but not with a clean syntax like the one above.
For example, you can use std::vector<std::vector<T>>
to represent your matrix.
std::vector<std::vector<int> > mat;
Then to add a column:
for (int i=0; i<mat.size(); i++) mat[i].push_back(col[i]);
or to add a row
mat.push_back(row); // row is a std::vector<int>
+1 for OpenCV, especially useful if you are doing image analysis, as it abstracts the underlying data type (GRAYSCALE, RGB, etc.).
C++ doesn't have a standard matrix class per-se. I think there were too many different uses of such a class that made a one-size-fit all solution impossible. There is an example and discussion in Stroustrup's book (The C++ Programming Language (Third Edition)) as to a simple implementation for a numerical matrix.
However, for image processing it's much better to use an existing library.
You might have a look at CImg. I've used it before and found it quick and well documented.
If you are on an AMD machine I know there is an optimised library for image processing from AMD, the Framewave project Framewave Project.
Also, if you are used to MATLAB style code then you may want to look at it++. I think the project aim is for it to be as similar to MATLAB as possible.
精彩评论