动态分配二维数组

时间:2012-07-07 20:06:06

标签: c++ dynamic multidimensional-array

  

可能重复:
  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 *'

如何让这两个版本的数组动态化?

2 个答案:

答案 0 :(得分:1)

最简单的方法是使数组成为一维,并自己计算指数。

伪代码:

int MaxWidth;
int MaxHeight;
int* Array;

Array=new int[MaxWidth*MaxHeight];

int Column, Row;
...

Element=Array[Row*MaxWidth+Column];

答案 1 :(得分:1)

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

他们的三维数组示例:

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