【问题标题】:Dynamically allocating a two-dimensional array [duplicate]动态分配二维数组
【发布时间】:2012-07-07 20:06:05
【问题描述】:

可能重复:
How do I use arrays in C++? (FAQ)
Using dynamic multi-dimensional arrays in c++

void fillTestCase (int * tC)
{
    ifstream infile;
    infile.open("input00.txt",ifstream::in);
    int * tempGrid;
    int i,j;
    infile >>i;
    infile >>j;
    tempGrid = new int[i][j];
}

给我一​​个错误:

error C2540: non-constant expression as array bound
error C2440: '=' : cannot convert from 'int (*)[1]' to 'int *'

如何使这两个维度数组动态化?

【问题讨论】:

标签: c++ dynamic multidimensional-array


【解决方案1】:

最简单的方法是使数组一维,然后自己计算索引。

伪代码:

int MaxWidth;
int MaxHeight;
int* Array;

Array=new int[MaxWidth*MaxHeight];

int Column, Row;
...

Element=Array[Row*MaxWidth+Column];

【讨论】:

  • 我认为你应该补充一下为什么他的代码不起作用。
【解决方案2】:

到目前为止,最好的方法是使用boost multidimensional array library。

他们的 3-d 数组示例:

int main ()
{
  // Create a 3D array
  typedef boost::multi_array<double, 3> array_type;
  typedef array_type::index index;

  for ( int x = 3; x < 5; ++x )
  {
      int y = 4, z = 2;

      array_type A(boost::extents[x][y][z]);

      // Assign values to the elements
      int values = 0;
      for(index i = 0; i != x; ++i) 
        for(index j = 0; j != y; ++j)
          for(index k = 0; k != z; ++k)
            A[i][j][k] = values++;

      // Verify values
      int verify = 0;
      for(index i = 0; i != x; ++i) 
        for(index j = 0; j != y; ++j)
          for(index k = 0; k != z; ++k)
            assert(A[i][j][k] == verify++);
    }

  return 0;
}

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 2013-11-24
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    相关资源
    最近更新 更多