c++ - 在 C++ 中转置矩阵

标签 c++ matrix transpose

我正在编写一个程序来使用分配的内存转置给定的矩阵。该函数与方阵 NxN (rows==cols) 完美搭配,但与 MxN 矩阵 (rows != cols) 搭配时会崩溃。请帮忙

void transpose(int **matrix, int *row, int *col)
{
    // dynamically allocate an array
    int **result;
    result = new int *[*col]; //creates a new array of pointers to int objects
    // check for error
    if (result == NULL)
    {
        cout << "Error allocating array";
        exit(1);
    }
    for (int count = 0; count < *col; count++)
    {
        *(result + count) = new int[*row];
    }

    // transposing
    for (int i = 0; i<*row; i++)
    {
       for (int j = i+1; j<*col; j++)
       {
        int temp = *(*(matrix + i) + j);
        *(*(matrix + i) + j) = *(*(matrix + j) + i);
        *(*(matrix + j) + i) = temp;
       }
    }

    for (int i = 0; i<*row; i++)
    {
       for (int j = 0; j<*col; j++)
       {
          *(*(result + i) + j) = *(*(matrix + i) + j);
          cout << *(*(result + i) + j) << "\t";
       }
       cout << endl;
    }
}

最佳答案

线条:

for (int i = 0; i<*row; i++)
{
   for (int j = i+1; j<*col; j++)
   {
    int temp = *(*(matrix + i) + j);
    *(*(matrix + i) + j) = *(*(matrix + j) + i);
    *(*(matrix + j) + i) = temp;
   }
}

是问题。问题是矩阵由 i 然后 j 索引,而不是 j 然后 i 就像你在 while 循环的第二行和第三行做的那样。图片那个矩阵是一个2x3的矩阵,然后你尝试执行matrix[2][3] = matrix[3][2],但是matrix[3][2]不存在。

最好直接在这个循环中简单地初始化结果:

for (int i = 0; i<*row; i++)
   for (int j = 0; j<*col; j++)
     result[j][i] = matrix[i][j];

然后你可以像下面这样输出,或者删除矩阵并重新分配矩阵作为你想要的结果。我的整个转置函数变成了下面的代码(row 和 col 不需要是指向 int 按值传递的指针就可以了。访问矩阵也应该使用数组下标,因为它是更好的样式):

void transpose(int **matrix, int row, int col)
{
  // dynamically allocate an array
  int **result;
  result = new int *[col]; //creates a new array of pointers to int objects
  for (int i = 0; i < col; i++)
    result[i] = new int[row];

  // transposing
  for (int i = 0; i<row; i++)
   for (int j = 0; j<col; j++)
     result[j][i] = matrix[i][j];

  //output resulting matrix
  for (int i = 0; i<col; i++) {
   for (int j = 0; j<row; j++)
    cout << result[i][j] << "\t";
   cout << endl;
  }
}

关于c++ - 在 C++ 中转置矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14846905/

相关文章:

c++ - 用于生成 pybind11 绑定(bind)的模板元函数

c - 如何计算行列式矩阵 2x2 -C

python - 我认为不存在索引错误

c# - 分解 3x3 矩阵

python - python 3.2.3 中的 Zip 函数无法正常工作

php - 从嵌套数组中提取数据

c++ - 在 C++11 和 C++17 中插入映射的方法?

c++ - 定义类模板构造函数并提供模板参数

c++ - Ctrl-C 对 C++ Win32 控制台应用程序究竟有什么影响?

arrays - 从键和值数组创建对象