如何在c ++中创建一个连续的2d数组? [英] how to create a contiguous 2d array in c++?

查看:151
本文介绍了如何在c ++中创建一个连续的2d数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,在C ++中返回一个连续的2D数组。

I want to create a function that returns a contiguous 2D array in C++.

使用命令创建数组不是一个问题:

It is not a problem to create the array using the command:

 int (*v)[cols] = new (int[rows][cols]);

但是,我不知道如何将此数组作为函数的一般类型返回。函数是:

However, I am not sure how to return this array as a general type for a function. The function is:

  NOT_SURE_WHAT_TYPE create_array(int rows, int cols)
  {
        int (*v)[cols] = new (int[rows][cols]);
        return v;
  }

我尝试double * []和double **, 。我不想使用double *,因为我想从外部访问这个数组作为一个二维数组。

I tried double*[] and double** and both don't work. I wouldn't want to use double*, since I want to access this array from outside as a 2D array.

相关问题:如何在C ++中使用new声明一个2d数组?


Related question: How do I declare a 2d array in C++ using new?

推荐答案

如果你想创建一个数据是连续的数组,而你不想要一个一维数组使用[] []语法),那么以下应该工作。它创建了一个指针数组,每个指针指向一个进入内存池的位置。

If you want to create an array where the data is contiguous and you don't want a 1-dimensional array (i.e. you want to use the [ ] [ ] syntax), then the following should work. It creates an array of pointers, and each pointer points to a position into a pool of memory.

template <typename T>
T** create2DArray(unsigned nrows, unsigned ncols)
{
   T** ptr = new T*[nrows];  // allocate pointers
   T* pool = new T[nrows*ncols];  // allocate pool
   for (unsigned i = 0; i < nrows; ++i, pool += ncols )
       ptr[i] = pool;
   return ptr;
}

template <typename T>
void delete2DArray(T** arr)
{
   delete [] arr[0];  // remove the pool
   delete [] arr;     // remove the pointers
}

int main()
{ 
   double **dPtr = create2DArray<double>(10,10);
   dPtr[0][0] = 10;  // for example
   delete2DArray(dPtr);  // free the memory
}

注意,只有2个分配完成。还要注意如何释放内存。你可以通过使这是一个真正的类,而不是将分配/释放作为2个单独的函数来改进设计。

Note that only 2 allocations are done. Also note how you deallocate the memory. You can improve on the design by making this a true class instead of having allocation / deallocation as 2 separate functions.

编辑:类不像RAII一样,就像评论说的。我把这作为一个练习给读者。上面的代码中缺少的一件事是在创建这样的数组时检查nRows和nCols> 0。

The class is not RAII-like, just as the comment says. I leave that as an exercise for the reader. One thing missing from the code above is the check that nRows and nCols are > 0 when creating such an array.

这篇关于如何在c ++中创建一个连续的2d数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆