转置期间的动态内存分配

时间:2012-11-30 15:07:05

标签: c++ matrix dynamic-memory-allocation

我正在尝试计算非n乘n的矩阵的转置。 问题是我必须为每个添加的元素分配新内存,我不必删除**数组。 代码是这样的。 //初始化二维数组。

array  = new int*[row];
    for (int i=0; i<row; i++){
        arr[i] = new int[col]();
    }

现在我只考虑一个假设我的矩阵是3 * 4的情况。 Matrix的转置具有暗淡的4 * 3。 我执行以下代码但是它给出了“SEGMENTATION FAULT”。我的想法是为元素分配一个新内存,该内存将作为转置结果添加。 代码是:

int r=col;
int c=row;
 if (col<c){
  arr  = new int*[row];
  for (int i=col; i<=c; i++){
  arr[i] = new int[col](); // trying to allocate New Memory to elem.
  }

这里给出错误。 任何帮助。如果还有其他方法可以解决这个问题,请做一下建议。

2 个答案:

答案 0 :(得分:3)

使用访问器函数(例如,矩阵的运算符(row,col))编写包装器,并在内部使用大小为rows * cols的一维数组。

它使事情变得更容易,并将此矩阵的数据保存在一起。这可以为较小的矩阵提供缓存优势。

以下是评论中要求的示例。它的用途非常简单,不使用任何模板。它使用向量作为内部存储。您可以使用运算符(..)访问矩阵元素,例如

Matrix A(3,4);
// fill matrix
// you can access each element in a natural syntax as expected from math
int x = A(2,2);
A(2,2) = 3;

此外,您可能应该使用异常而不是断言来检查索引溢出。

// matrix.h
#include <vector>

class Matrix
{
public:
  Matrix(size_t rows, size_t cols);

  int& operator()(size_t row, size_t col);
  const int& operator()(size_t row, size_t col) const;

  int& operator[](size_t index);
  const int& operator[](size_t index) const;

  Matrix get_transposed() const;

  size_t compute_index(size_t row, size_t col) const;

  void print();

private:
  size_t  _rows;
  size_t  _cols;

  std::vector<int>  _data;

}; // class Matrix



// matrix.cpp 
#include "matrix.h"
#include <iostream>
#include <cassert>

Matrix::Matrix(size_t rows, size_t cols)
  : _rows(rows)
  , _cols(cols)
  , _data(rows*cols, 0)
{
}


int& Matrix::operator()(size_t row, size_t col)
{
  const size_t index = compute_index(row, col);
  assert(index < _data.size());
  return _data[index];
}

const int& Matrix::operator()(size_t row, size_t col) const
{
  const size_t index = compute_index(row, col);
  assert(index < _data.size());
  return _data[index];
}


int& Matrix::operator[](size_t index)
{
  return _data[index];
}

const int& Matrix::operator[](size_t index) const
{
  return _data[index];
}

size_t
Matrix::compute_index(size_t row, size_t col) const
{
  // here you should check that: 
  // row < rows
  // col < cols
  // and throw an exception if it's not
  assert(row<_rows);
  assert(col<_cols);

  return row * _cols + col;
}

Matrix
Matrix::get_transposed() const
{
  Matrix t(_cols,_rows); 

  for(size_t row = 0; row < _rows; ++row)
    for(size_t col = 0; col < _cols; ++col)
    {
      t(col,row) = (*this)(row,col);
    }
  return t;
}

答案 1 :(得分:3)

在第二个代码示例中,您将覆盖数组限制。 arr元素row元素长,从0row - 1。在for循环中,您的索引icol变为c,相当于row和数组之外的一个元素。正确的代码是<而不是<=

for (int i=col; i < c; i++){
    arr[i] = new int[col](); // trying to allocate New Memory to elem.
}

除此之外,我可以建议您查看Wikipedia: Transpose,因为在第二种情况下,您可以使用第一个代码示例,只需要行和列切换。