Converting 2D vector to 2D array

梦想与她 提交于 2021-02-19 01:14:57

问题


It's been a while since I last visited arrays (I've been working with vectors recently) and I need to convert an 2D vector back into a 2D array because of a library I am using accepts the paramaters of type double array where the accessors of this array is foo[i][j] for example.

Here is my code:

double** setupHMM(vector<vector<double> > &vals, int N, int M)
{
  double** temp;
  temp = new double[N][M];

 for(unsigned i=0; (i < N); i++)
 {
    for(unsigned j=0; (j < M); j++)
    {
        temp[i][j] = vals[i][j];
    }
 }
}

And with this, I get error: ‘M’ cannot appear in a constant-expression

I have also tried the following:

double** setupHMM(vector<vector<double> > &vals, int N, int M)
{
   double** temp;

   for(unsigned i=0; (i < N); i++)
   { 
      temp[i] = new double[N];
      for(unsigned j=0; (j < M); j++)
      {
          temp[j] = new double[M];
          temp[i][j] = vals[i][j];
      } 
   }
 }

However, this produces a segmentation fault 11.

Could anyone suggest any advice, or, a better way to convert a vector to a 2D array..

Thanks


回答1:


You were close. It should be:

double** setupHMM(vector<vector<double> > &vals, int N, int M)
{
   double** temp;
   temp = new double*[N];
   for(unsigned i=0; (i < N); i++)
   { 
      temp[i] = new double[M];
      for(unsigned j=0; (j < M); j++)
      {
          temp[i][j] = vals[i][j];
      } 
   }
 }



回答2:


A double pointer (double**) is not convertible to a 2D array.

double** temp;
temp = new double[N][M];  //invalid


double** temp;
temp = new double(*)[M];

It's a common misunderstanding to think that because an 1D array decays to a pointer that therefore a 2D array will decay to a double pointer. This is not true. The decay only happens with a single pointer.




回答3:


replace

temp[i] = new double[N];

with

temp = new double*[N];

in the second code, and move it outside the loop



来源:https://stackoverflow.com/questions/15295677/converting-2d-vector-to-2d-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!