C++ 内存分配。矩阵

标签 c++ memory dynamic matrix allocation

我研究了两种不同的方法来为矩阵的元素分配内存

方法一

int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
    matrix[i] = new int[cols];

方法二

int** matrix = new int*[rows];
if (rows)
{
    matrix[0] = new int[rows * cols];
    for (int i = 1; i < rows; ++i)
        matrix[i] = matrix[0] + i * cols;
}

我可以弄清楚方法 n.1 的作用,但我无法弄清楚方法 n.2 中的 if 子句究竟应该做什么(我会在没有的情况下实现它,但它不起作用,使用if 子句,它确实...)

编辑:这是显示我的问题的代码。为什么加载需要这么长时间(~30 秒)?

http://codepad.org/uKvI8Tk3

Codepad 拒绝显示输出(超时),因此如果您想运行它,只需自行编译即可。

另外,为什么cout <<语句在程序启动后不执行?

最佳答案

方法 n.3:编写自己的 Matrix 类,在内部使用单个 std::vector<int>并巧妙地通过(行,列)索引进行访问。

struct Matrix
{
  explicit Matrix(unsigned int rows, unsigned int cols) : data_(rows*cols), cols_(cols) {}
  const int& operator()(unsigned int row, unsigned int col) const
  {
    return data_[row*cols_ + col];
  }
 private:
  std::vector<int> data_;
  unsigned int cols_;
};

编辑:iff vector 的内存开销是上一个示例中的一个问题,您可以考虑使用长度为 rows*cols 的单个动态分配数组, 并确保调用 delete []在析构函数中对其进行处理。

关于C++ 内存分配。矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14926763/

相关文章:

python - python 中的 MemoryError 分块上传

html - css动态图标布局无需刷新,类似amazon网站

linux - 第二次插件崩溃时再次引用代码段

c# - 当右侧操作数是泛型时, "as"运算符如何翻译?

android - 使用 Opencv 从 Android 中的 CameraGLSurfaceView 拍照

c++ - 内部类和初始化

linux - 32 位 RHEL 机器上的内存使用

c++ - cuda 共享内存 - 结果不一致

c++ - QVector::remove(int i, int count) 从第一个移除时的性能

c++ - 带有类型别名的函数指针参数