I have created a function to flip a square 2d array horizontally, so the first row is moved to the last, the second row is moved to the second from the last and so on.
Here is the function:
void flipMatrix(int size, int matrix[ROWS][COLS]) {
int row, col;
int temp[ROWS][COLS];
for (row=0; row < size; row++) {
for (col=0; col < size; col++) {
temp[(size - 1)-row][col] = matrix[row][col];
}
}
//A simple function that copies the temp array to matrix, so that
//I can then print the matrix array
copyArray(size, matrix, temp);
}
I know that this is very inefficient, but I am pretty new to C++. I was wondering how I would adapt this to be more efficient, maybe b开发者_运维知识库y returning a pointer? I'm also wondering if there is a way to do this without creating a temporary array?
I should also note, I am trying to do this without using the STL.
Thanks for the help.
You can use std::swap
and just swap the values in-place:
void flipMatrix(int size, int matrix[ROWS][COLS])
{
for (int row = 0; row < ROWS; ++row)
{
for (col=0; col < COLS / 2; ++col) // half the column, lest you undo it
{
std::swap(matrix[ROWS - row - 1][col], matrix[row][col]);
}
}
}
Swap is defined in <algorithm>
. If you really can't use STL, swap is simple enough to implement:
template <typename T>
void swap(T& pA, T& pB)
{
T temp = pA;
pA = pB;
pB = temp;
}
If you can use a different data structure to represent the matrix, you can get a more efficient algorithm without using STL.
For example, consider using an array of pointers to a list of arrays, each of which represents a matrix row. With this data structure, you only need to swap the pointer if the first array and don't need to touch items in the array list.
Copying the values back to matrix wont copy the values back to the caller of flipMatrix
, since arrays with known size (here, ROWS x COLS
) are passed by value:
void copyReverse(int a[4]) { ... }
void refReverse(int a[], int size) { ... }
int a[4] = { 1, 2, 3, 4 };
copyReverse(a);
// a = { 1, 2, 3, 4 } still.
refReverse(a, 4); // Doesn't know size from type
// a = { 4, 3, 2, 1 }
So combining this with GMan's answer, expanding the swap:
void flipMatrix(int size, int matrix[][])
{
for (int row = 0; row < size; ++row)
{
for (col=0; col < size / 2; ++col)
{
int temp = matrix[size - row - 1][col];
matrix[size - row - 1][col] = matrix[row][col];
matrix[row][col] = temp;
}
}
}
精彩评论