简体   繁体   English

将2D矢量转换为2D数组

[英]Converting 2D vector to 2D array

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. 自从我上次访问数组以来已经有一段时间了(我最近一直在使用向量)并且我需要将2D向量转换回2D数组,因为我正在使用的库接受类型为double array的参数,其中包含例如,这个数组是foo[i][j]

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 有了这个,我得到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. 然而,这产生了分段错误11。

Could anyone suggest any advice, or, a better way to convert a vector to a 2D array.. 任何人都可以建议任何建议,或者更好的方法将矢量转换为2D数组..

Thanks 谢谢

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];
      } 
   }
 }

A double pointer ( double** ) is not convertible to a 2D array. 双指针( double** )不可转换为2D数组。

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. 认为因为1D阵列衰减到指针因此2D阵列将衰减为双指针是一种常见的误解。 This is not true. 这不是真的。 The decay only happens with a single pointer. 衰变只发生在一个指针上。

replace 更换

temp[i] = new double[N];

with

temp = new double*[N];

in the second code, and move it outside the loop 在第二个代码中,将其移出循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM