[英]How to set according to the x-axis Symmetry of Matrix
I need a function that can take to according to the x-axis of symmetry of the matrix. 我需要一个可以根据矩阵对称性的x轴使用的函数。
input (matrix[i][j]): 输入(矩阵[i] [j]):
1 2 3
4 5 6
7 8 9
output (matrix[i][j]): 输出(矩阵[i] [j]):
7 8 9
4 5 6
1 2 3
How can i do this on the same matrix? 如何在同一矩阵上执行此操作? How should I write the inverse function?
我应该如何编写逆函数?
void inverse(.......)
{
..
..
..
}
int main(){
int **matrix, i, j, k, row, column;
cout << "Row and column:" ;
cin >> row >> column;
matrix = new int*[row];
for (i=0; i<row; ++i){
matrix[i] = new int[column];
}
cout << "input elements of matrix: " << endl;
for(i=0; i<row; i++){
for (j=0; j<column; j++){
cin >> *(*(matrix+i)+j);
}
}
inverse (........);
for(i=0; i<row; i++){
for (j=0; j<column; j++){
cout << *(*(matrix+i)+j);
}
cout << endl;
}
return 0;
}
In this particular case, you can modify the loop to print the matrix backwards: 在这种情况下,您可以修改循环以向后打印矩阵:
for(i = 0; i < row; i++) {
-> ->
for(i = row - 1; i >= 0; i--) {
But if you want to actually do something to the data, my suggestion would be to refactor this code to use std::vector
. 但是,如果您想对数据做一些实际的事情,我的建议是将代码重构为使用
std::vector
。
std::vector<std::vector<int> > matrix(numberOfRows, std::vector<int>(numberOfColumns));
// You can use std::vector<std::valarray<int> > matrix; alternatively.
You would then flip it simply by using an STL function: 然后,您只需使用STL函数将其翻转:
std::reverse(matrix.begin(), matrix.end());
Edit: 编辑:
Well, if you don't want to use std::vector
for the time being and for this particular case, what you would do is this: 好吧,如果您暂时不想使用
std::vector
,并且在这种情况下,您可以这样做:
void flipMatrix(int** matrix, int rows, int columns) {
int middle = rows/2; // I expect it to truncate for an odd number of rows.
// Temporary row for swapping
int* tempRow;
for (int i = 0; i < middle; i++) {
// swap rows
tempRow = matrix[i];
matrix[i] = matrix[rows - i - 1];
matrix[rows - i - 1] = tempRow;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.