Coding Tip: selecting a row from a matrix in managed C++
I decided to update my blog now and then with coding tips for various languages I work in. These will usually be my own solutions for problems on which I can’t immediately find a clear answer on.
This first tip is specifically for writing managed C++ (in Microsoft’s Visual C++).
Suppose you have a function that accepts a managed integer array as a parameter.
void foo(array<int>^ row);
And suppose you have a managed integer matrix.
array<int, 2>^ matrix = {{1,2,3},{3,4,5},{6,7,8},{9,10,11}};
How do you pass a row (e.g. row 2) from this matrix to that function?
One way to do this, is by using native pointers. You could pin the matrix in the memory using the pin_ptr keyword (see MSDN library) and then pass a pointer to the function as an int*.
(with thanks to “Alex F” from the CodeGuru forums)
Another way is to use the following function I wrote:
array<int>^ getRowFromMatrix(array<int, 2>^ matrix, int row) { array<int>^ rowArray = gcnew array<int>(matrix->GetLength(1)); for (int i=0; i<matrix->GetLength(1); i++) rowArray[i] = matrix[row, i]; return rowArray; }
Easy, right?
Posted in Programming |