C/C++实现矩阵的转置(示例代码)

时间:2022-06-15 04:16:03

废话不多说,直接上代码

复制代码 代码如下:


#include <iostream>
using namespace std;

 

const int N = 5;

int matrix[5][5] =
{
    1,2,3,4,5,
    1,2,3,4,5,
    1,2,3,4,5,
    1,2,3,4,5,
    1,2,3,4,5
};

void swap(int &a,int &b)
{
    a=a^b;
    b=a^b;
    a=a^b;
}
void matrix_transpose(int m[N][N])
{
    int i,j;
    for(i=1;i<N;i++)
    {
        for(j=0;j<i;j++)
            swap(m[i][j],m[j][i]);
    }
}
void print(int m[N][N])
{
    int i,j;
    for(i=0;i<N;i++)
    {
        for(j=0;j<N;j++)
            cout<<m[i][j]<<"  ";
        cout<<endl;
    }
}

int main()
{
    cout << "Hello world!" << endl;
    int a=10;
    int b=13;
    swap(a,b);
    cout<<"交换过之后:"<<"\ta :"<<a<<"\tb:"<<b<<endl;
    print(matrix);
    matrix_transpose(matrix);
    cout<<"交换过顺序之后:"<<endl;
    print(matrix);
    return 0;
}