中堆上的2D矩阵分配

中堆上的2D矩阵分配

本文介绍了C ++中堆上的2D矩阵分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在堆中元素为连续的堆上分配2D(m x n)矩阵的方法.目前,我知道有两种方法可以做到这一点:

I am looking for a way to allocate a 2D (m x n) matrix on the heap where the elements are consecutive in memory. Currently I know of two ways to accomplish that:

int* M = new int[m * n];

  • Pro:M的大小可以动态确定.
  • 缺点:M的索引有点麻烦. (M[i * m + j])
    • Pro: The size of M can by dynamically determined.
    • Con: Indexing of M is a bit of a pain. (M[i * m + j])
    • typedef int dim[2];
      dim* M = new dim[n];
      

      • Pro:M的索引编制正是我想要的.
      • 缺点:第一维(m)的大小无法动态设置.
        • Pro: Indexing of M is just how I want it to be.
        • Con: The size of the first dimension (m) cannot be set dynamically.
        • 是否有一种方法可以在堆上动态分配2D矩阵,我可以在其中使用[i][j] 索引元素,并且内存分配是连续的?

          Is there a way to allocate a 2D matrix dynamically on the heap where I can index the elements with [i][j] and the memory allocation is consecutive?

          我知道为此使用一个类很有意义,但是我正在专门寻找一种如上所述的方法.

          I know it would make a lot of sense to use a class for that, but I am specifically looking for a way as described above.

          推荐答案

          您可以尝试

          int** M = new int*[m];
          int *M_data = new int[m*n];
          
          for(int i=0; i< m; ++i)
          {
              M[i] = M_data + i * n;
          }
          

          这篇关于C ++中堆上的2D矩阵分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:30