转置整数方阵

Problem

Transpose an integer array

Solution

#include <iostream>

using namespace std;

int** create_matrix(int row, int col)
{
    int **m = new int* [row];
    for(int i = 0; i < row; i++){
        m[i] = new int[col];
    }

    return m;
}

void delete_matrix(int** m, int row)
{
    for(int i = 0; i < row; i ++){
        delete[] m[i];
    }

    delete []m;
}

void print_matrix(int** m, int row, int col)
{
    for(int i = 0; i < row; i ++){
        for(int j = 0; j < col; j++){
            cout << m[i][j] << "  ";
        }
        cout << endl;
    }
}

void initial_matrix(int **m, int row, int col)
{
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j ++){
            m[i][j] = rand() % 100;
        }
    }
}

void transpose_matrix(int **mat, int row, int col)
{
    int i, j;
    for(i= 0; i< row; i++){
        for(j=i+1; j< col; j++){
            int tmp = mat[i][j];
            mat[i][j] = mat[j][i];
            mat[j][i] = tmp;
        }
    }
}

int main(int argc, char* argv[])
{
    int size = 6;

    int **m = create_matrix(size, size);
    int i,j;

    initial_matrix(m, size, size);
    cout << "before transposing" << endl;
    print_matrix(m, size, size);

    transpose_matrix(m, size, size);

    cout << "after transposing" << endl;
    print_matrix(m, size, size);

    return 0;
}

Output

before transposing
41  67  34  0  69  24
78  58  62  64  5  45
81  27  61  91  95  42
27  36  91  4  2  53
92  82  21  16  18  95
47  26  71  38  69  12
after transposing
41  78  81  27  92  47
67  58  27  36  82  26
34  62  61  91  21  71
0  64  91  4  16  38
69  5  95  2  18  69
24  45  42  53  95  12



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值